• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

452
Vistas
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

almost 3 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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} />;
   
     })}
  )
}
almost 3 years ago · Juan Pablo Isaza Denunciar

0

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={...} />;
almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda