I have some images in my project folder and want to either use their relative links to show them in each respective array item.
I want to eventually use the image in a react component to show the image on my webpage.
File Structure
- src
- assets
- data
- project.js
- projectImages.js
- images
- img.jpg
- img2.jpg
- img3.jpg
- data
- components
- Project.jsx
- assets
Project.jsx
export default function Project({ project, theme }) {
return (
<div id="project">
<h3 className="subheading">{project.name}</h3>
<div>
<img src={project.img}>
</div>
</div>
);
}
project.js
// import projectImages from '../data/projectImages' (tried to import an array of img)
module.exports = [
{
type: "",
name: "",
desc: "",
tech: ["", "", "", ""],
summary: "",
year: ,
img: '../data/images/img.jpg', // tried projectImages[0]
link: "",
},
{
...
img: '../data/images/img2.jpg', // tried projectImages[1]
...
},
{
...
img: '../data/images/img3.jpg', // tried projectImages[2]
...
},
I have tried to import img from '../data/projectImages/img.jpg
but the variable was not accepted in the object array.
I have also tried to shove the images into an array and use the array to reference them but that did not work as well.
2
Answers
You are using
create-react-app
which useswebpack
behind the scenes.It’s been a while since I did this, but I believe that you can do something like:
const myRequireContext = require.context('./someDir', false, /.jpg$/);
which will give you an object that looks something like:
(this is off-the-top-of-my-head, so details might be a little different)
See https://webpack.js.org/guides/dependency-management/#require-with-expression
Directly inside your array, use require()