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

205
Visualizações
How to find the positions and width/heights of react components?

I am trying to build a react app, and what I am trying to do is have the app, and have a section/component within it, which I will need the positioning and width and height of. But when I try to use document.getElementById('area').getBoundingClientRect().width (to find the width for example), I am not able target the component. Instead, my code seems to fail unless I use document.getElementById('root').getBoundingClientRect().width.

My file:

import './App.css';

class App extends React.Component {
  render() {
    return (
      <main>
        <Space />
      </main>
    );
  }
}

class Space extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div class="space">
        <h1>{document.getElementById('root').getBoundingClientRect().width}</h1>
      </div>
    );
  }
}

export default App;

I have to use 'root' instead of 'area' for it to work. A "Space" is just an area that I need to know the coordinates of. Thanks.

Edit: Here is the file with the id="root":

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="src/favicon.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite App</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

In most cases, you should use a react ref to get the element, not document.getElementById. For example, this code renders a div, and then in componentDidMount can access the underlying DOM element:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.mainDiv = React.createRef();
  }

  componentDidMount() {
    console.log(this.mainDiv.current.getBoundingClientRect().width);
    // Possibly set state to rerender now that you know the width
  }

  render() {
    return (
      <div ref={this.mainDiv}>
        Hello World
      </div>
    );
  } 
}

getElementId can sometimes be useful if you need to get an element that's outside of the react component tree, but that's uncommon. If you're trying to use getElementId and it's not working, make sure an element with that id exists. Your question didn't show any elements with the ids "root" or "area", so check to make sure those are part of the page.

about 4 years ago · Juan Pablo Isaza Relatório

0

To access the DOM properties in react there is a concept in react called refs.Refs allow us to directly access the dom elements. So refer this codesandbox to know how to make it work in FUNCTIONAL COMPONENT with useRef hook.

Refer This, will explain with code and also see the console in the sandbox:

LINK

Also this might explain more theoritically : LINK

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