Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

171
Visualizações
Creating image and simultaneously displaying its dimensions in React

I am trying to create an image (based on src) and also show its dimensions at the same time.

I tried

const DisplayImage = () => {
 const [src,setSrc]=useState('');

 return (
   <div>
    {src===''?'':<img id='my-img' src={image} alt='some text' />}
    {document.getElementById('my-img')?.naturalHeight}
   </div>);
 }

Of course, it's not working (the image does not exist when I try to find its height).

I also tried to do it in a JavaScript way, creating an Image() and calling document.appendChild to the document, but it is probably not the right way of doing it in React.

Is there a better way of doing it?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use a callback ref, and store the values in a state variable to display them later using a useEffect() hook or similar. For example:

const [ imageHeight, setImageHeight ] = useState(null);
const [ imageWidth, setImageWidth ] = useState(null);
const [ imageSource, setImageSource ] = useState(null);

const imageMeasurements = useCallback(image => {
    if (image !== null) {
      setImageWidth(image.naturalWidth);
      setImageHeight(image.naturalHeight);
    }
}, [ ]);

return (
  <div>
    { imageSource !== null && (
      <img ref={ imageMeasurements } src={ imageSource } alt="some text" />
    )}

    { (imageWidth !== null && imageHeight !== null) && (
      <span class="image__dimensions">{imageWidth} x {imageHeight}</span>
    )}
  </div>
);
about 4 years ago · Juan Pablo Isaza Relatório

0

I'd like to post the solution I ended up with, because even though @BenM answered my question perfectly, the solution did not work for me for naturalWidth/naturalHeight props. They were shown as zeros.

I think the problem is that those props are populated only after the image is fully loaded, as described here.

To get it working, I placed the logic in onLoad instead, so my code looks like:

const [imageSource,setImageSource]=useState('');


const [ imageHeight, setImageHeight ]=useState(null);
const [ imageWidth, setImageWidth ]=useState(null);   
const imgRef = React.createRef();


<div> { imageSource !== null && (
   <img 
     src={imageSource} 
     alt='should be something'
     ref={imgRef}
     onLoad={() =>{ setImageHeight(imgRef.current.naturalHeight); 
                    setImageWidth(imgRef.current.naturalWidth); }
            }
    /> 
   { imageWidth &&
     <div 
      className="image_dimensions">
      Image size: {imageWidth} x {imageHeight}
     </div>
   })
</div>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda