How to render image from data object? (React) - reactjs

guys!
I have object with images.
I need to go through the object and render images from there. (I will have plenty of them).
Here is my js file:
const myJson = {
"data": [
{
"id": 1,
"name": "Landscape of Saint-Remy",
"path": "./a.jpg",
"cost": 400,
},
{
"id": 2,
"name": "Landscape of Saint-Remy",
"path": "./b.jpg",
"cost": 400,
},
{
"id": 3,
"name": "Landscape of Saint-Remy",
"path": "./c.jpg",
"cost": 400,
},
]
}
export default myJson;
I try to render it in my Home component like this:
import React from 'react';
import myJson from '../../server/myJson';
function Home() {
return (
<div>
<Hi />
{myJson.data.map(key => (
<img src={require(`${key.path}`)} key={key} />
))}
</div>
)
But got an error: Module can't be found.
If I render images like this:
<img src={key.path} key={key} />
I see 200ok, but no image because I need to import it and that is why I used require to import image and use it. But it's not working.
Please, help me!

This is not the way to import images, you need to config you webpack and add file-loader or url-loader to require images inside your javascript.
Take a look at this answer:
https://stackoverflow.com/a/37673142/5497628

Here this is how you can do it
const myJson = {
"data": [
{
"id": 1,
"name": "Landscape of Saint-Remy",
"path": require("./a.jpg"),
"cost": 400,
},
{
"id": 2,
"name": "Landscape of Saint-Remy",
"path": require("./b.jpg"),
"cost": 400,
},
{
"id": 3,
"name": "Landscape of Saint-Remy",
"path": require("./c.jpg"),
"cost": 400,
},
]
}
export default myJson;
This is how you have to prepare json data.
import React from 'react';
import myJson from '../../server/myJson';
function Home() {
return (
<div>
<Hi />
{myJson.data.map(key => (
<img src={key.path} key={key} />
))}
</div>
)
This is how you can render it.

Related

#React Import an image in a component

i'm trying to define my "Logo" as an image.
i tried to create a logo.js component, define it as an image and call it here, but i have absolutely no clue on how to solve that.
Here is my banner component,
import React from 'react'
import Banner from 'react-banner'
import 'react-banner/dist/style.css'
import Logo from '../Logo'
export default props => {
return (
<Banner
Logo = "My logo"
url={ window.location.pathname }
items={[
{ "content": "Quoi de neuf au tieks ?", "url": "/wassup" },
{ "content": "Les poucaves du jour", "url": "/lpdc", "children": [
{ "content": "Océane", "url": "/children/oceane" },
{ "content": "Mehdi", "url": "/children/mehdi" },
{ "content": "Yikes", "url": "/children/zemmeled" }
]}
]} />
)
}
if I understand well your question is: I can you pass a logo to the Banner Component ?
A quick look to the react-banner documentation and you can find :
"logo (node)
The image, text, or whatever else you may want to display in the left section of the banner.
url (string)"
https://skipjack.github.io/react-banner/customization
So I believe you can do as follow:
import React from 'react'
import Banner from 'react-banner'
import 'react-banner/dist/style.css'
import Logo from '../Logo'
export default props => {
return (
<Banner
Logo = "My logo"
logo=<Logo />
url={ window.location.pathname }
items={[
{ "content": "Quoi de neuf au tieks ?", "url": "/wassup" },
{ "content": "Les poucaves du jour", "url": "/lpdc", "children": [
{ "content": "Océane", "url": "/children/oceane" },
{ "content": "Mehdi", "url": "/children/mehdi" },
{ "content": "Yikes", "url": "/children/zemmeled" }
]}
]} />
)
}
As you can see on the code above, I pass the Logo component into the props logo of the BannerComponent from the librairy react-banner.

How do I iterate over a JSON file in react?

I'm new to React and for the life of me cannot figure this out.
I have a JSON file (Fontawesome icons):
{
"icons": [
{
"name": "Glass",
"id": "glass",
"unicode": "f000",
"created": 1,
"filter": [
"martini",
"drink",
"bar",
"alcohol",
"liquor"
],
"categories": [
"Web Application Icons"
]
},
{
"name": "Music",
"id": "music",
"unicode": "f001",
"created": 1,
"filter": [
"note",
"sound"
],
"categories": [
"Web Application Icons"
]
},
// etc
To start with I just want to return the name of each icon.
I've been trying to follow various tutorials and have:
import React, { PureComponent } from "react";
import iconList from './services/iconList';
export default class App extends PureComponent {
render() {
const items = iconList.map(data=>{
return(
<div>
<ul>
<li>
<span>{data.name}</span>
</li>
</ul>
</div>
)
})
return items;
}
}
But I get the error: .map is not a function.
I'm not sure what I can do differently. Each tutorial I see seems to use the map function. Is there a better/different way?
Try using
const items = iconList.icons.map(data=>{
Your data is an object with an icons property in it. You can also destructure your iconList when you import:
import {icons as iconList } from './services/iconList';

"TypeError: Cannot read property 'name' of undefined" when looping on JSON

I have a JSON like this :
{
"cards": [
{
"name": "aquaman",
"img": "aquaman.png"
},
{
"name": "batman",
"img": "batman.png"
},
{
"name": "captainamerica",
"img": "captainamerica.png"
},
{
"name": "deadpool",
"img": "deadpool.png"
},
{
"name": "flash",
"img": "flash.png"
},
{
"name": "greenlantern",
"img": "greenlantern.png"
},
{
"name": "ironman",
"img": "ironman.png"
},
{
"name": "spiderman",
"img": "spiderman.png"
},
{
"name": "ironfist",
"img": "ironfist.png"
},
{
"name": "thepunisher",
"img": "thepunisher.png"
},
{
"name": "wonderwoman",
"img": "wonderwoman.png"
},
{
"name": "xman",
"img": "xman.png"
}
]
}
and I want to loop on these objects and to render a div with a backgroundImage with the img property of every object,
I tried this, but it tells me:
TypeError: Cannot read property 'name' of undefined
import React, { useEffect, useState } from "react";
import cardsJson from "../../../utils/cards.json";
const [cards, setCards] = useState();
useEffect(() => {
setCards(cardsJson.cards);
}, [cards]);
{cards &&
cards.map((card: any, index: number) => (
<div key={card.name} className="cardHero">
<div className="front"></div>
<div
className="back"
style={{
backgroundImage: `url(${require(`../../../assets/images/${card.img}`)})`
}}
></div>
</div>
))}
It looks like inside the map I can't get name or img for every card ?? And when I console log "cards", it show me the JSON like above with name and img properties
Assuming your code is wrapped in a function component (see below), it may be an issue with how you're importing / using cards.json. Also in the useEffect, make the dependency array [] instead of [cards]. I changed your code to this and it works:
import React, { useEffect, useState } from "react";
import cardsJson from "./cards.json";
export function Cards() {
const [cards, setCards] = useState();
useEffect(() => {
console.log(cardsJson);
setCards(cardsJson.cards);
}, []);
return (
<div>
{
cards &&
cards.map((card, index) => (
<div key={card.name} className="cardHero">
<div className="front">{card.name}</div>
<div
className="back"
></div>
</div>
))
}
</div>
);
}
Note I put the cards.json in the same folder as the Cards component, I'm not outputting the image and I updated the dependency array.
If you only want to display the cards there is no reason for them to be inside a useEffect. I recommend you to create a constant and initialize it with cardsJson.cards, like:
const cards = cardsJson.cards;
Or if you want to play with states, just initialize your state with cardsJson.cards, like:
const [cards, setCards] = useState(cardsJson.cards);

React react-icons-kit and get Icons dynamically

How to get Icons dynamically in React using extension React Icon kit? I try to find out the way to add a icon dynamically in a MAP-loop as I get them from array "sociallinks"
here is the part of the code
....
import { Icon } from 'react-icons-kit'
import {facebook} from 'react-icons-kit/feather/facebook';
import {instagram} from 'react-icons-kit/feather/instagram';
import {twitter} from 'react-icons-kit/feather/twitter';
....
// dynamic array from redux store
"sociallinks": [
{
"_id": 1,
"type": "facebook",
"linkname": "Facebook",
"link": "https://www.facebook.com/zzzzz/"
},
{
"_id": 2,
"type": "instagram",
"linkname": "Instagram",
"link": "https://www.instagram.com/yyy/"
},
{
"_id": 3,
"type": "twitter",
"linkname": "Twitter",
"link": "https://twitter.com/xxx"
},
{
"_id": 4,
"type": "youtube",
"linkname": "Youtube",
"link": "https://www.youtube.com/user/youtube"
}
]
// problem is here how to markup icon = {xxxxx} from map item.type? item.link and item.linkname works fine.. but not item.type :(((
<ul>
{this.props.data.socialLinks.map((item,i) => (
<li key = {i}> <a href = {item.link}><Icon size={18} icon={item.type} />{item.linkname}</a></li>
))
}
</ul>

Right way to parse Redux state props - using super json objects

Following my trip with React and Redux, I'm facing a problem, simple in appearance, but hard to solve : I'm setting my Redux state with a very big JSON object. Those datas are retrieved from an async call. When I'm setting it, I created an entry in my reducer with
let initialState = {
pages: []
}
Then, I'm putting different pages, with their params and datas into this pagesarray. So far so good, the state is well updated.
BUT, my different app pages use only parts of it as you can imagine. For instance, I have a page named Gallery which might need my state to look like this :
"pages": [
{
"component":"Gallery",
"key": "gallery",
"title": "Galerie photos",
"url": "/galerie-photos",
"sections": [
{
"component": "Gallery",
"params": {
"images": [
{
"id": 1,
"src": "http://lorempicsum.com/futurama/627/300/1",
"alt": "alternate text"
},
{
"id": 2,
"src": "http://lorempicsum.com/futurama/500/400/2",
"alt": "alternate text"
},
{
"id": 3,
"src": "http://lorempicsum.com/futurama/400/320/3",
"alt": "alternate text"
},
{
"id": 4,
"src": "http://lorempicsum.com/futurama/800/500/4",
"alt": "alternate text"
},
{
"id": 5,
"src": "http://lorempicsum.com/futurama/320/300/5",
"alt": "alternate text"
},
{
"id": 6,
"src": "http://lorempicsum.com/futurama/420/360/6",
"alt": "alternate text"
}
]
}
}
]
}
]
In my GalleryContainer, I'm requesting only the images property as this is the only concern of my Gallery component. I'm able to retrieve this data with no problem. Testing with the following code returns the desired images array :
But as far as I tested this, the images are not retrieved by my Gallerycomponent : when console logging on the component side, I got undefined, and on the container side, no problem.
I tested something different : I set a galleryImages property via the reducer, and set it with the gallery images directly. This worked.
The questions are : Why doesn't it work in the first case, and do in the second ? Do I have to work only with datas that are set as state properties only ? Can't I have a "super" json set in my state to work with directly ?
Thanks to light me up on this one :)
// Component
import React from 'react'
const Gallery = ({images}) => (
<div>
{images.map((image, key) =>
<div key={key} className="image-element-class" style={card}>
<img src={image.src} alt={image.alt} style={imageStyle}/>
</div>
)}
</div>
)
const card = {
width: 'calc((100% / 3) - (15px / 1.5))',
marginBottom: '15px',
boxSizing: 'border-box'
}
const imageStyle = {
width: '100%'
}
export default Gallery
// Container
import { connect } from 'react-redux'
import Gallery from '../../components/pages/Gallery'
const getImages = state => {
return {
images: state.data.pages.filter(page => page.component === 'Gallery' &&(
page.sections.filter(section => section.component === 'Gallery' &&(
section.params.images
))
)),
}
}
const mapStateToProps = state => {
return getImages(state)
}
const GalleryContainer = connect(
mapStateToProps,
{}
)(Gallery)
export default GalleryContainer
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script>

Resources