简体   繁体   中英

Why is document.getElementById() returning null in React although element is there in React?

I have this code inside a React class component and when I try calling document.getElementById(photo._id) it keeps returning null although when I tried console.log(photo._id) in both lines, the line in the render is printed first in the console so the id is supposed to be there?

componentDidMount() {
    this.props.location.state.product.photos.map((photo) => {
      return axios
        .get(`${SERVER_HOST}/products/photo/${photo.filename}`)
        .then((res) => {
          if (res.data) {
            if (res.data.errorMessage) {
              console.log(res.data.errorMessage);
            } else {
              console.log(photo._id);
              console.log(document.getElementById(photo._id));
            }
          } else {
            console.log("Record not found");
          }
        });
    });
  }

render() {
    return (
    {this.props.location.state.product.photos.map((photo) => {
         { console.log(photo._id); }
         <img key={photo._id} id={photo._id} />;
   
     })}
  )
}

Here is a picture of the console

You are not returning the image element in map function. Hence, it's not mounted in the dom tree and you can't access it using document.getElementById()

render() {
    return (
    {this.props.location.state.product.photos.map((photo) => {
         { console.log(photo._id); }
          {/** return keyword is missing here **/}
         return <img key={photo._id} id={photo._id} />;
   
     })}
  )
}

Replace your render function body with the code below.

return this.props?.location?.state?.product?.photos?.map((photo) => 
   <img key={photo._id} id={photo._id} src={...} />;

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