Home > Software design >  Why is document.getElementById() returning null in React although element is there in React?
Why is document.getElementById() returning null in React although element is there in React?

Time:02-25

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

CodePudding user response:

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} />;
   
     })}
  )
}

CodePudding user response:

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={...} />;
  • Related