简体   繁体   中英

Import images in react in a loop

What I am trying to accomplish is importing each file from the proper directory. My backend code saves files to the images directory, and my frontend directory is where I hold my React.js code.

The structure of my directory can be seen below.

-- Backend
   -- backend code
-- Frontend
   -- frontend code
-- images
   -- user_1
      -- People.jpg
   -- user_2
      ...

As you can see, I am getting the path from the backend. imagePath will look something like this "../images/user_1/People.jpg". I saw another stackoverflow post store the image in const variable using the require keyword, but I received an error using that method.

@observer
export default class SnapCapsule extends React.Component {
  componentDidMount() {
    axios.get(`${this.props.domain}/snapcapsule`)
      .then(res => {
        res.data.map((capsule) => {
          var domainSize = this.props.domain.length+13;
          var imagePath = "../" + capsule["image"].substring(domainSize);
          var dateToPost = capsule["dateToPost"].substring(0, 10);
          var username = capsule["username"];
          console.log(capsule["caption"], imagePath, dateToPost, username);
          this.props.store.addCapsule(
            capsule["caption"],
            imagePath,
            dateToPost,
            username
          )
        })
      });
  }

  componentWillUnmount() {
    this.props.store.clear();
  }


  render() {
    const { capsules } = this.props.store;
    const capsuleList = capsules.map((capsule, i) => (
    <Col key={i} xs={6} md={4}>
      <Thumbnail src={capsule.imagePath} alt="242x200">
        <h3> {capsule.title} </h3>
        <p> @{capsule.username} </p>
      </Thumbnail>
    </Col>
  ));

return (
  <Grid>
    <Row>
      { capsuleList }

    </Row>
  </Grid>
);

}

    return (
      <Grid>
        <Row>
          { capsuleList }

        </Row>
      </Grid>
    );
  }
}

Answer

Instead of providing a path to the image tag in the directory. I configured the backen to be retrieved photos through urls.

capsule.imagePath => http://localhost:8000/snapcapsule/images/user_1/People.jpeg

I suggest avoid dynamic require for dynamic condition. While bundling you it may not include all your image and may cause issue.

In your condition, you are fetching information from server and trying to import file directly from folder which is not correct way. As web application you should use a web url to show images.

In response of capsuleList, you have image path. Use that path and your backend should handle request and return image. It's backend responsibility. While react running on browser, react don't have permission to access folder but your backend can access folders.

In your backend, read image and server it.

You should be able to actually reference those images directly in your thumbnail component without importing it as a module or anything like that.

const path = "./../../images/user_1/People.jpg";
<Thumbnail src={path} ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM