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

154
Visualizações
Why getting cannot read properties of undefined error?

I have a react app in which I am supposed to get users from an API endpoint: <reqres.in>.

I am supposed to return as many buttons on the homepage as the number of users I get on fetching the users from the API.

Also I am constrained not to add event listeners to all buttons and just add one listener to the wrapper for the buttons. The code for the same is:

const ButtonContainer = ({ users }) => {
    // const navigate=useNavigate();
    const wrapper = document.getElementById('wrapper');
    wrapper.addEventListener('click', (event) => {
        const isButton = event.target.nodeName === 'BUTTON';
        if (!isButton) {
            return;
        }
        // navigate(`/singleuser/${event.target.id}`);
    })

    return (
        <div id='wrapper'>
            {
                users.map((user, idx) => {
                    return (
                        <button key={idx} id={idx}>
                            User {idx}
                        </button>
                    )
                })
            }
        </div>
    )
}

export default ButtonContainer

users is the array of users Im getting from the API.

However I am getting the error:

Cannot read properties of null (reading 'addEventListener')

What should I do?

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

0

Using native DOM methods with React won't give you the result you want as React has its own way of managing the DOM.

Add an onClick to your wrapper element:

<div onClick={handleClick}>

and then have handleClick deal with the event.

function Example({ users }) {

  function handleClick(e) {

    // Because we're using event delegation [1]
    // check if the clicked element was a user button
    if (e.target.matches('button.user')) {

      // Extract the id from its dataset,
      // and log it
      const { id } = e.target.dataset;
      console.log(`User: ${id}`);
    }
  }

  return (
    <div onClick={handleClick}>
      {users.map(user => {
        return (
          <button
            key={user.id}
            className="user"
            data-id={user.id}
          >User: {user.id}
          </button>
        );
      })}
    </div>
  );

}

const users = [{ id: 1 }, { id: 2 }, { id: 3 }];

ReactDOM.render(
  <Example users={users} />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></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