0

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>
   );
};
Reillo
  • 11
  • 5
  • Can you post the relevant code? – jnpdx Mar 21 '21 at 21:22
  • Why not serve them as static assets as in public folder? And you can store their relative path in your JSON – ilkerkaran Mar 21 '21 at 21:23
  • Does this answer your question? [How to import image (.svg, .png ) in a React Component](https://stackoverflow.com/questions/43823289/how-to-import-image-svg-png-in-a-react-component) – Alexey Nikonov Mar 21 '21 at 21:29
  • That's what I'm eventually trying to do (currently I'm just trying to reference a svg in the same file) but it keeps throwing errors at me... – Reillo Mar 21 '21 at 21:30

2 Answers2

0

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>
   );
};
Yadab
  • 1,767
  • 1
  • 10
  • 16
0

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.

Damien
  • 644
  • 4
  • 11