V
V
Vlad2021-03-31 21:44:00
JavaScript
Vlad, 2021-03-31 21:44:00

React. Why does an element in a component become empty?

I am learning React.

import './Header.scss';
import React from 'react';

const menuBtn = document.querySelector('.btn');
console.log(menuBtn);

function Header() {
  return (
    <>
      <div className="menu">
        <div className="btn">
        {/* ... */}
      </div>
    </>
  );
}

export default Header;


Why when you write lines
const menuBtn = document.querySelector('.btn');
console.log(menuBtn);

and you save the component file, then this object is displayed in the console, but when you update via F5, the menuBtn element becomes null?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Denioo, 2021-03-31
@Denioo

Because the component is updated from top to bottom, i.e. when you update the component, the line first fires

const menuBtn = document.querySelector('.btn');
console.log(menuBtn);

And then the component is loaded, move the lines down if it matters or call in the component itself
function Header()

V
Vladimir, 2021-03-31
@Casufi

Why do you need to get an element through a selector? Right now your code doesn't make sense because Virtual DOM
In functional components, if you need access to the real home use the useRef hook
https://reactjs.org/docs/hooks-reference.html#useref

B
Buck, 2021-04-01
@Buck

as an option

class Header extends React.Component {

  componentDidMount() {
    const menuBtn = document.querySelector('.btn');
   console.log(menuBtn);
  }

  render() {  
    return (
    <>
      <div className="menu">
        <div className="btn">
        {/* ... */}
      </div>
    </>
    )
  }
}
export default Header;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question