can't Load local files dynamically in react js - reactjs

I want to load some local images dynamically in my app. I have a json with records like
{name: image12, poster: 'image1.jpg'}, {name: image13, poster: 'image2.jpg'}
I have a folder with many images like 'image1.jpg', 'image2.jpg', 'image3.jpg'. When I try to render the json record i put
<img src={'./image/image1.jpg'}/> but it is not working.
[![import React from 'react';
const Poster = (props) => {
return(
<div className="individual-poster">
<h2>{props.postData.name}</h2>
<img src={'./Slices/'+props.postData["poster"]} width="100px" height="100px"/>
</div>
);
}
image is not even listing in the source list also.

if you know path images then your json object you trying to map must be somewhat similar to this:
const obj = [
{"name":"Chrysanthemum","path":require('./Chrysanthemum.jpg')}, //this will work
{"name":"Desert","path":'./Desert.jpg'}, //will not work
]
require your path to images must be inside require mehtod.
Use like considering json obj file exported as default in same directory with file name imagesJson.
import imagArray from './images';
map like this
imagArray.map((m)=>{
return <div>
{m.name}
<img src={m.path}/>
</div>
})

If you created you react app with create-react-app then you can import image variable and later use it multiple time.
import logo from './logo.png' // relative path to image
class App extends Component {
render() {
return (
<img src={logo} alt={"logo"}/>
)
}
}
or you can directly specify image relative path.
<img src ="http://localhost:3000/img/foo.png" />
<img src="/details/img/bar.png" />
In your question for use images from array
const images = [{
name: 'image12',
path: 'image1.jpg'
}, {
name: 'image13',
path: 'image2.jpg'
}];
class App extends Component {
render() {
return (
<div>
<img src={logo} alt={"logo"}/>
{images.map((img) => <img src={img.post} alt={img.name} />)}
</div>
)
}
}

Related

Can I reference component props to get from parent when I am supposed to provide child component with props?

I am working o a project with multiple carousels.
so I decided to create a carouselitem.js component, a carousel.js component that includes multiples item component slides, a slides.js files with all items data.
the idea is to provide data about carousel slides in slides.js file then map them to the item component so when an object in added to the file it gets automatically to the carousel.
import Carousel from "react-bootstrap/Carousel";
function Carouselslideitem(props) {
return (
<Carousel.Item>
<img className="d-block w-100" src={props.image} alt={props.alter} />
<Carousel.Caption>
<h3>{props.header}</h3>
<p>{props.description}</p>
</Carousel.Caption>
</Carousel.Item>
);
}
export default Carouselslideitem;
above is the item component as you see it is supposed to get props parent component carouselslide.js which is defined as follows
import Carousel from "react-bootstrap/Carousel";
import Carouselslideitem from "./Carouselslideitem.js";
function Carouselslider(props) {
return (
<Carousel fade>
{props.list.map((e) => {
return (
<Carouselslideitem
image={e.slide}
alter={e.alter}
header={e.header}
description={e.description}
/>
);
})}
</Carousel>
);
}
export default Carouselslider;
this is the slide.js files containing the carousel data
[enter image description here][3]
const image1 = "../images/homeslider/1.png";
const image2 = "../images/homeslider/2.png";
const image3 = "../images/homeslider/3.png";
const slides = [
{
slide: image1,
alter: "slide1",
header: "Header1",
description: "Desc 1",
},
{
slide: image2,
alter: "slide 2",
header: "header2",
description: "desc2",
},
{
slide: image3,
alter: "slide3",
header: "header3",
description: "desc3",
},
];
export default slides;
and finally the app.js component
import Navigationbar from "./components/Navbar";
import Carouselslider from "./components/Carouselslider";
import slides from "./components/slides.js";
function App() {
return (
<div className="App">
<Navigationbar />
<Carouselslider list={slides} />
</div>
);
}
export default App;
the things that makes worry is whether I will be able to pass the list props from app.js to carouselslideitem.js through carouselslide.js
To sum it up, I am trying to import the data from slides.js to the app.js component and pass it as list props to carouselslide.js which uses the data and maps it to carouselslideitem.js component and display a slide for each object represented on slides.js
I am thinking this way I will be able to create a carousel for each data fileps: I am currently getting this errors from the console(see screenshot!)
I hope the code is clear and easy to read.
and thank you.

'Cannot Find Module' when using an Image in React

I am using React and I am running into an issue importing images in a component. Now I know how to use the import method, which is fine for some things but in this case the image src is part of an array of objects I need to map over.
So let me start with if I do this directly: <img src={require('../../images/leadinvestigator.jpg')} /> It works just fine.
However if I do this: <img src={require(member.image)} /> or <img src={require(${member.image})} /> I get:
react-dom.development.js:11340 Uncaught Error: Cannot find module '../../images/leadinvestigator.jpg'
and if I do this: <img src={require({member.image})} /> I get an invalid token error
here is my component code:
import React from "react"
import "react-responsive-carousel/lib/styles/carousel.min.css"
import { Carousel } from 'react-responsive-carousel'
import './styles.css'
const Crew = () => {
const crewMembers = [
{
image: '../../images/leadinvestigator.jpg',
name: 'Bryant Richards',
title: 'Lead Investigator',
quote: 'In the end, it only matters what you believe'
}
]
return (
<Carousel
showArrows={true}
infiniteLoop={true}
showThumbs={false}
showStatus={false}
autoPlay={true}
interval={6100}
>
{
crewMembers ? crewMembers.map(member => (
<div>
<img src={require('../../images/leadinvestigator.jpg')} />
<div className="myCarousel">
<h3>{member.name}</h3>
<h4>Designer</h4>
<p>
It's freeing to be able to catch up on customized news and not be
distracted by a social media element on the same site
</p>
</div>
</div>
)) : null
}
</Carousel>
)
}
export default Crew
Try to import your image before put it in the object.
Add on top of your component:
import bryantImage from '../../images/leadinvestigator.jpg'
and then add this image to your object like that:
const crewMembers = [
{
image: bryantImage,
name: 'Bryant Richards',
title: 'Lead Investigator',
quote: 'In the end, it only matters what you believe'
}
]

Why local svg icons not resolve in react.js projects?

I have local icons, and I add icons in build folder like screenshot below, then I was import icons like that import {ReactComponent as MyIcon} from "build/icons/my-icon.svg";, but still say "Can't resolve 'build/icons/my-icon.svg'", any idea?
Screenshot:
you need to use file-loader
and when you import dont use brackets since its default export just chose the name directly
import myIcon from "build/icons/my-icon.svg";
const App = () => {
return (
<div className="App">
<img src={myIcon} />
</div>
);
}
Svg tag
second option would be to extract the svg tag and put it directly into you component ,
const App = () => {
return (
<div className="App">
<svg .... // copy the content of your .svg
</svg>
</div>
);
}

Best way to pass images in static react app

I'm using react to create a web-app that has to be static so no API calls and I need to store some data client-side (I'm currently just using a single JSON file as it's really not large) but I'm struggling to pass images down, I'm storing the references as strings in the JSON file and passing them to the props but I'm getting all sorts of errors. Is there a better or more practical way to do this?
Code (I've added a variable to imitate the JSON structure):
const HomePage = () => {
let projectInfo: ProjectInfo = {
title: "Project",
description:
"A progressive web app.",
imgURL: "./TODO", //<- HERE
mainColour: "#323232",
secondaryColour: "#464646",
};
return (
<div id="carousel-container">
<Carousel labels={["1"]}>
<ProjectPanel info={projectInfo} />
</Carousel>
</div>
);
};
export default HomePage;
interface IProjectPanelProps {
info: ProjectInfo;
}
const ProjectPanel = (props: IProjectPanelProps) => {
return (
<div className="project-panel">
<h2>{props.info.title}</h2>
<p>{props.info.description}</p>
<img src={/* ?? */} alt=""></img>
</div>
);
};
You can use base64 images to store them.
See this post https://stackoverflow.com/a/42399865/1356340 for examples of how to use binary images in React.
You can import your image in your home page as a variable and pass that variable to your child component.
import myImage from 'your_image_path';
const HomePage = () => {
let projectInfo: ProjectInfo = {
title: "Project",
description:
"A progressive web app.",
imgURL: myImage
mainColour: "#323232",
secondaryColour: "#464646",
};
return (
<div id="carousel-container">
<Carousel labels={["1"]}>
<ProjectPanel info={projectInfo} />
</Carousel>
</div>
);
};
export default HomePage;
interface IProjectPanelProps {
info: ProjectInfo;
}
const ProjectPanel = (props: IProjectPanelProps) => {
return (
<div className="project-panel">
<h2>{props.info.title}</h2>
<p>{props.info.description}</p>
<img src={info.imgURL} alt=""></img>
</div>
);
};

Displaying images with webpack using require.context

I have made my first React app using Webpack with the create-react-app tool.
I have an unknown amount of images in a folder I would like to display as my apps background at random. Using some code from the Webpack docs and other threads I use this code in my component.
import React, { Component } from 'react';
import './styles/css/App.css';
function requireAll(r) {
r.keys().forEach(r);
var images = r.keys();
images = images.map( path => "./images/backgrounds/" + path );
console.log(images);
return images;
}
var images = requireAll(require.context('./images/backgrounds/', true, /\.jpg$/));
let randomIndex = Math.floor(Math.random() * images.length) + 0;
var randomImgRef = images[randomIndex];
class App extends Component {
render() {
return (
<div className="App" style={{backgroundImage: "url(" + randomImgRef + ")"}} >
<h1>hi</h1>
</div>
);
}
}
export default App;
This seems to work, the background style has the right path and my console logs the right path also. But no images are displayed, and I'm clueless.
I think Webpack might not be including the images in the build, though the code I'm using seems like it should do that. So I'm clueless.
Any ideas?
I think for your example you just have to use randomImgRef.default so use the default property to get the url.
EXAMPLE Using require.context to display images:
const photos = importAll(require.context('../../assets/photos', false, /\.(png|jpe?g|svg)$/));
Render:
<div>
{photos.map((photo, i) => (
<div className="photo" key={i}>
<img src={photo.default} alt=`photo-${i}` />
</div>
))}
</div>

Resources