I cannot connect image from Json file with React Js - javascript

I am new with ReactJs and I cannot solve the problem to connecting image path with react from separate Json file and it is only showing image icon. I don't understand is there problem with image path or with css code (! but I did not write css for image ^^) or another... ?
src
components -- "folder name"
postCard.js
data -- "folder name"
datastore.json
img_reactjs01 -- "folder name"
Katana.png
App.js
My code
postCard.js
import React, { Component } from "react";
import qData from "../data/datastore.json";
class Quotes extends Component{
render(){
return(
<div className="card-stl" onmouseover="this.bgColor='white'">
{
qData && qData.map((s)=>{
return(
<div className="post_Card" key={s.id}>
<picture className="card__picture">
<img src={s.image} alt={s.name} />
</picture>
<h2>{s.name}</h2>
<p>{s.price}</p>
<p>{s.description}</p>
</div>
)
})
}
</div>
)
}
}
export default Quotes;
datastore.json
[
{
"id": 1,
"name": "Product 1",
"image": "../img_reactjs01/Katana.png",
"price": "$20",
"description": "This is a description of Product 1"
},
{
"id": 2,
"name": "Product 2",
"image": "https://pin.it/5i1L9ZG",
"price": "$30",
"description": "This is a description of Product 2"
},
{
"id": 3,
"name": "Product 3",
"image": "https://pin.it/2pfRfgY",
"price": "$40",
"description": "This is a description of Product 3"
}
]
App.js
import Quotes from "./components/postCard";
function App() {
return (
<div className="App">
<Quotes />
</div>
);
}
export default App;
!Sorry for my English

This is because your image links are not links to images but links to pages containing images, try inserting the following as the first json element and it should work:
{
"id": 1,
"name": "Product 1",
"image": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1200px-Image_created_with_a_mobile_phone.png",
"price": "$20",
"description": "This is a description of Product 1"
}

Related

How to create a new custom carousel component from a PrimeNG carousel?

I am trying to create a generic component in my project which uses the NgPrime Carousel bases (such as indicators, navigators, etc) and only has to modify the HTML content of the items from my parent component.
Stackblitz Demo Code From PrimeNG
I don't know if what I'm trying to do is possible but I'm looking to try to do it since the generic component I'm creating has several common methods and css styles that will be repeated every time a carousel must be created
Code example of what I'm trying to do
// CustomCarouselComponent.ts
#Input() products
#Input() responsiveOptions
<!-- CustomCarouselComponent.html -->
<p-carousel [value]="products" [numVisible]="3" [numScroll]="3" [responsiveOptions]="responsiveOptions">
<ng-content ></ng-content>
</p-carousel>
//ParentComponent.ts
products = [
{
"id": "1000",
"code": "f230fh0g3",
"name": "Bamboo Watch",
"description": "Product Description",
"image": "https://cdn.pixabay.com/photo/2017/05/09/03/46/alberta-2297204__340.jpg",
"price": 65,
"category": "Accessories",
"quantity": 24,
"inventoryStatus": "INSTOCK",
"rating": 5
},
{
"id": "1001",
"code": "nvklal433",
"name": "Black Watch",
"description": "Product Description",
"image": "https://cdn.pixabay.com/photo/2017/05/09/03/46/alberta-2297204__340.jpg",
"price": 72,
"category": "Accessories",
"quantity": 61,
"inventoryStatus": "INSTOCK",
"rating": 4
}
]
responsiveOptions = [
{
breakpoint: '1024px',
numVisible: 3,
numScroll: 3
},
{
breakpoint: '768px',
numVisible: 2,
numScroll: 2
},
{
breakpoint: '560px',
numVisible: 1,
numScroll: 1
}
];
<!-- ParentComponent.html -->
<custom-carousel [products]="products" [responsiveOptions]="responsiveOptions">
<ng-template let-product pTemplate="item">
<div class="product-item">
<div class="product-item-content">
<div class="p-mb-3">
</div>
<div>
<h4 class="p-mb-1">{{product.name}}</h4>
<h6 class="p-mt-0 p-mb-3">${{product.price}}</h6>
<span [class]="'product-badge status-'+product.inventoryStatus.toLowerCase()">{{product.inventoryStatus}}</span>
</div>
</div>
</div>
</ng-template>
</custom-carousel>

How to return JSON data in a list after retrieving it from a URL source?

My colleague and I are creating a simple directory app for departments and hit a roadblock - we can't successfully post the data from our database after trying to implement the data from our database directly into the app.
We were able to use dummy data for proof of concept and now having a difficult time trying to get the real data to show up. The data is being retrieved and parsed as a JS Object format which should be exactly what we were using before, however we're getting the error of:
Line 42:22: 'person' is not defined. no-undef
Here's what we have for our code:
App.js
import React from 'react';
import '../scss/App.css';
import PeopleList from './components/PeopleList';
import Accordion from "./components/Accordion";
import "../scss/main.scss";
class App extends React.Component {
render() {
return (
<div id="app">
<h1>Address Book</h1>
<PeopleList /> {/*The component we're having issues with */}
<Accordion addresses={addresses} />
</div>
)
}
}
export default App;
PeopleList.js
import React from 'react';
import axios from 'axios';
import '../../scss/App.css';
// let person = [
// {
// "division": "Town 1",
// "deptName": "Department 1",
// "name": "Pluto",
// "title": "Title 1",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 2",
// "deptName": "Department 2",
// "name": "Pluto",
// "title": "Title 2",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 3",
// "deptName": "Department 3",
// "name": "Pluto",
// "title": "Title 3",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 4",
// "deptName": "Department 4",
// "name": "Pluto",
// "title": "Title 4",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 5",
// "deptName": "Department 5",
// "name": "Pluto",
// "title": "Title 5",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 6",
// "deptName": "Department 6",
// "name": "Pluto",
// "title": "Title 6",
// "phone1": "(123) 456-7890",
// },
// ];
class PeopleList extends React.Component {
state = {
person: []
}
componentDidMount() {
axios({
method: 'GET',
url: '/phonebook/all'
})
.then((res) => {
console.log(res.data)
const person = res.data;
console.log(person)
const obj = JSON.parse(person);
console.log(obj)
this.setState({ person });
})
};
constructor() {
super();
this.state = {
search: ''
}
};
render() {
return (
<>
<div className="people-list">
<ul className="list">
{person.map((p)=> {
return (
<li>
<p>
{p.name} <br />
{p.title} <br />
{p.phone1} <br />
{p.division}
</p>
</li>
)
})}
</ul>
</div>
</>
)
}
}
export default PeopleList
With the given axios call, we're under the impression person is being defined as a JS Object class just like our dummy data, but the error message states otherwise. We're successfully able to console.log() the data per the calls during the axios call when we comment out the person.map() part in the return so we know the data is being returned, but not sure what we're missing to have the data be returned on the client side. Any help on this is greatly appreciated.
Updated the constructor and axios call - our data is now returning!!
PeopleList.js
import React from 'react';
import axios from 'axios';
import '../../scss/App.css';
// let person = [
// {
// "division": "Town 1",
// "deptName": "Department 1",
// "name": "Pluto",
// "title": "Title 1",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 2",
// "deptName": "Department 2",
// "name": "Pluto",
// "title": "Title 2",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 3",
// "deptName": "Department 3",
// "name": "Pluto",
// "title": "Title 3",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 4",
// "deptName": "Department 4",
// "name": "Pluto",
// "title": "Title 4",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 5",
// "deptName": "Department 5",
// "name": "Pluto",
// "title": "Title 5",
// "phone1": "(123) 456-7890",
// },
// {
// "division": "Town 6",
// "deptName": "Department 6",
// "name": "Pluto",
// "title": "Title 6",
// "phone1": "(123) 456-7890",
// },
// ];
class PeopleList extends React.Component {
// state = {
// person: []
// }
componentDidMount() {
axios({
method: 'GET',
url: '/phonebook/all'
})
.then((res) => {
this.setState({ person:res.data });
})
};
constructor() {
super();
this.state = {
search: '',
person: []
}
};
render() {
return (
<>
<div className="people-list">
<ul className="list">
{this.state.person.map((p)=> {
return (
<li>
<p>
{p.name} <br />
{p.title} <br />
{p.phone1} <br />
{p.division}
</p>
</li>
)
})}
</ul>
</div>
</>
)
}
}
export default PeopleList

how to fetch nested api data in ReactJS?

i am trying to solve this problem is, whenever user will click on category title then user will redirect to another page and will see the product_set data as per category id or slug.
i am probably new to ReactJs, it would be great if anybody could help me out what i am trying to solve is. thank you so much in advance.
end point url: "http://localhost:8000/api/p_category"
Api data:
[
{
"id": 1,
"title": "category01",
"slug": "category01",
"description": "",
"image": "http://localhost:8000/media/cat2_KpMV1YQ.jpg",
"product_set": [
{
"url": "http://localhost:8000/api/p/product01",
"id": 1,
"title": "product01",
"slug": "product01",
"image": "http://localhost:8000/media/product2_EMWEgQI.png",
"price": 5,
"status": true,
"created_on": "2020-04-19T18:44:03Z"
},
]
},
{
"id": 3,
"title": "category03",
"slug": "category03",
"description": "category03 desc..",
"image": "http://localhost:8000/media/cat3_9dal1uP.jpg",
"product_set": [
{
"url": "http://localhost:8000/api/p/product03",
"id": 3,
"title": "product03",
"slug": "product03",
"image": "http://localhost:8000/media/product5.png",
"price": 3,
"status": true,
"created_on": "2020-04-19T18:44:03Z"
},
{
"url": "http://localhost:8000/api/p/product06",
"id": 5,
"title": "product06",
"slug": "product06",
"image": "http://localhost:8000/media/product6_rkmAlce.png",
"price": 12,
"status": true,
"created_on": "2020-04-19T18:44:03Z"
}
]
}
]
You can do like this,
import { React } from "react";
class categoryListExample extends React.Component{
state={
categoryList:[],
category:''
}
async componentDidMount(){
let res=await fetch("http://localhost:8000/api/p_category")
//assuming you are getting data in response.data
this.setState({categoryList:res.data})
}
categoryChangeHandler=(category)=>{
this.setState({category})
}
render(){
const {categoryList,category}=this.state
if (categoryList.length>0) {
return(
<div>
<ul>
{categoryList.map(category=><li key={category.id} onClick={this.categoryChangeHandler}>{category.title}</li>)}
</ul>
<CategoryComponent category={category.product_set}/>
</div>
)
} else {
return(
<div>
Loading...
</div>
)
}
}
}
export default categoryListExample;

How to display, add and delete items from JSON file using ReactJs

I am using ReactJs and I am trying to create CRUD app that will be able to delete, display and add item to JSON file. With ReactJs I am also using Redux. I am trying to learn how to use ReactJs and Redux together.
JSON file will act like server.
This is my structure for now:
index.js
const logger = createLogger();
const store = createStore(combineReducers({roomReducer}), {}, applyMiddleware(logger));
ReactDOM.render(
<Provider store = {store}>
<BrowserRouter>
<App/>
</BrowserRouter>
</Provider>,
document.querySelector("#root")
);
App.js
export default class App extends React.Component {
render() {
return (
<div>
<Route path="/" exact component={LandingPage} />
</div>
)
}
}
REDUCERS
index.js
import {combineReducers} from 'redux';
import rooms from '../templates/rooms/Rooms';
const roomsReducer = combineReducers({
rooms
});
export default roomsReducer;
roomReducer.js
const initialState = {
rooms: []
};
export default function cardReducer(state = initialState, action) {
switch (action.type){
case 'ADD_ROOM':
return {
...state,
rooms: [
...state.rooms,
action.rooms
]
}
case 'REMOVE_ROOM':
//not sure how to do it
case 'FETCH_ROOMS':
return Object.assign({}, state, {
cards: action.rooms
});
default:
return state;
}
}
ACTIONS
roomActions.js
export function fetchRooms(){
return {
type: 'FETCH_ROOMS'
}
}
export function addRoom(){
return {
type: 'ADD_ROOM'
}
}
export function removeRoom(id){
return {
type: 'REMOVE_ROOM',
id: id
}
}
db.json
{
"cards": [
{
"id": 0,
"image": "http://placehold.it/400x300",
"title": "CATEGORY 0",
"numberGuests": "Placeholder 0",
"type": "Single"
},
{
"image": "http://placehold.it/400x300",
"title": "CATEGORY AAAA",
"numberGuests": "Placeholder BBB",
"type": "Single",
"id": 6
},
{
"image": "http://placehold.it/400x300",
"title": "CATEGORY AAAA",
"numberGuests": "Placeholder BBB",
"type": "Single",
"id": 7
}
]
}
This code is what I have came up by now. I have created store in my index.js file and connected it to my rooms.js component
class Rooms extends React.Component{
render(){
return(
<div>
hello
</div>
);
}
}
const mapStateToProps = (state) => {
return{
room: state.roomReducer
};
};
export default connect(mapStateToProps)(Rooms);
I hope I did it correctly. I am not sure how to now add, delete or list rooms that I have already in db.json file.
Any advice or guideline is highly appreciated.
let dbjson = {
"cards": [
{
"id": 0,
"image": "http://placehold.it/400x300",
"title": "CATEGORY 0",
"numberGuests": "Placeholder 0",
"type": "Single"
},
{
"image": "http://placehold.it/400x300",
"title": "CATEGORY AAAA",
"numberGuests": "Placeholder BBB",
"type": "Single",
"id": 6
},
{
"image": "http://placehold.it/400x300",
"title": "CATEGORY AAAA",
"numberGuests": "Placeholder BBB",
"type": "Single",
"id": 7
}
]
};
let state = {};
//You have cards in state
state['rooms'] = dbjson.cards;
// add room
let roomItem = {
"image": "http://placehold.it/400x300",
"title": "CATEGORY AAAA",
"numberGuests": "Placeholder BBB",
"type": "Single",
"id": 8
};
let rooms = [...state.rooms,roomItem];
state['rooms'] = rooms;
//dispatch
// remove room by index
let index = 1;
let roomstodelete = [...state.rooms];
roomstodelete.splice(1,index);
state['rooms'] = roomstodelete;
//dispatch
// remove room by id
let roomstodeleteByid = [...state.rooms].filter(vl=>vl.id!==8);
state['rooms'] = roomstodeleteByid;
//dispatch

React: Need help changing the data and html used on click of looped through data

I am new to react and now rewriting my personal web portfolio to learn it better. I'm having trouble getting the detail view to show for each project. When you click div className="view" I would like a detail page to call the json in say web.subContent with it's images and subtitle.
Currently when you click the li in nav id="nav" I get the state of the page to change and the content changes the top level json from web to print or photo in data.json.
Im sure I'm doing a lot wrong here and would love any help I can get in making this work correctly. Here is a link to all the code in my github. https://github.com/fitzmx6/reactportfolio/tree/master/coryfitzpatrick
content.js
import React from 'react';
import portfolioData from '../data/data.json';
export default class Content extends React.Component {
constructor(props) {
super(props);
this.state = {activeCategory: portfolioData.web};
}
render() {
var mainContent;
if (this.state.activeCategory === portfolioData.contact) {
mainContent = <div className="content">
<div className="grid-d-12">
<h1>Contact Me</h1>
<p>Bio Here...</p>
</div>
</div>;
} else {
mainContent = <div className="content">
{this.state.activeCategory.map(category => (
<div className="grid-d-4 grid-t-6 grid-panel cs-style-3">
<a href="/">
<figure>
<img src={category.imagePath} title={category.imageTitle} alt={category.name} />
<figcaption>
<h2>{category.name}</h2>
<div className="view">View</div>
</figcaption>
</figure>
</a>
</div>
))}
</div>
}
// else {
// mainContent = <div className="content">
// <div className="grid-12">
// <h1>portfolioData.web[0].subContent.subtitle</h1>
// </div>
// </div>
// }
return (
<div>
<div className="header">
<div className="grid-d-12">
<div id="logo">
<a href="/">
<h1>Cory Fitzpatrick |</h1>
<h2>Web Developer</h2>
</a>
</div>
<nav id="nav">
<ul>
<li onClick={() => this.setState({ activeCategory: portfolioData.web })} className="menu-item">Web</li>
<li onClick={() => this.setState({ activeCategory: portfolioData.print })} className="menu-item">Print</li>
<li onClick={() => this.setState({ activeCategory: portfolioData.photo })} className="menu-item">Photography</li>
<li onClick={() => this.setState({ activeCategory: portfolioData.contact })} className="menu-item">Contact</li>
</ul>
</nav>
</div>
</div>
{mainContent}
</div>
);
}
}
data.json
{
"web": [
{
"name": "Web 1",
"imagePath": "../images/cramer-thumb.jpg",
"subContent": {
"subTitle": "Cramer",
"images": [
"../images/cramer-thumb.jpg",
"../images/cramer-thumb.jpg",
"../images/cramer-thumb.jpg"
],
"link": "www.cramer.com"
}
}, {
"name": "Web 2",
"imagePath": "../images/earx-thumb.jpg",
"subContent": {
"subTitle": "Cramer",
"images": [
"../images/cramer-thumb.jpg",
"../images/cramer-thumb.jpg",
"../images/cramer-thumb.jpg"
],
"link": "www.cramer.com"
}
}, {
"name": "Web 3",
"imagePath": "../images/inlight-thumb.jpg",
"subContent": {
"subTitle": "Cramer",
"images": [
"../images/cramer-thumb.jpg",
"../images/cramer-thumb.jpg",
"../images/cramer-thumb.jpg"
],
"link": "www.cramer.com"
}
}
],
"print": [
{
"name": "Print 1",
"imagePath": "../images/earx-thumb.jpg",
"subContent": {
"subTitle": "Cramer",
"images": [
"../images/cramer-thumb.jpg",
"../images/cramer-thumb.jpg",
"../images/cramer-thumb.jpg"
],
"link": "www.cramer.com"
}
}, {
"name": "Print 2",
"imagePath": "../images/inlight-thumb.jpg",
"subContent": {
"subTitle": "Cramer",
"images": [
"../images/cramer-thumb.jpg",
"../images/cramer-thumb.jpg",
"../images/cramer-thumb.jpg"
],
"link": "www.cramer.com"
}
},{
"name": "Print 3",
"imagePath": "../images/cramer-thumb.jpg",
"subContent": {
"subTitle": "Cramer",
"images": [
"../images/cramer-thumb.jpg",
"../images/cramer-thumb.jpg",
"../images/cramer-thumb.jpg"
],
"link": "www.cramer.com"
}
}
],
"photo": [
{
"name": "Photo 1",
"imagePath": "../images/cramer-thumb.jpg",
"subContent": {
"subTitle": "Cramer",
"images": [
"../images/cramer-thumb.jpg",
"../images/cramer-thumb.jpg",
"../images/cramer-thumb.jpg"
],
"link": "www.cramer.com"
}
}, {
"name": "Photo 2",
"imagePath": "../images/inlight-thumb.jpg",
"subContent": {
"subTitle": "Cramer",
"images": [
"../images/cramer-thumb.jpg",
"../images/cramer-thumb.jpg",
"../images/cramer-thumb.jpg"
],
"link": "www.cramer.com"
}
}, {
"name": "Photo 3",
"imagePath": "../images/earx-thumb.jpg",
"subContent": {
"subTitle": "Cramer",
"images": [
"../images/cramer-thumb.jpg",
"../images/cramer-thumb.jpg",
"../images/cramer-thumb.jpg"
],
"link": "www.cramer.com"
}
}
],
"contact": {
"name": "Cory Fitzpatrick",
"bio": "I am Awesome!"
}
}
You should start to split your app in component,
for example a component header, content, contact,
and for your state, instead of having 4 different you just have the same onClick button who check the label of the li and then set a unique state of the content to show for example

Categories

Resources