-1

Simple question . How can I use Vanilla JS in my React Component?

For exemple:

This is not working, but WHY ??

function Home() {
    const title = document.querySelector('h1');
    console.log(title)                 // undefined

  return (
    
      <div >
        <h1>Pouet</h1>
      </div>
  );
}
  • Take a look [here](https://stackoverflow.com/questions/46160461/how-do-you-set-the-document-title-in-react). – bruxo00 Jan 15 '21 at 09:28
  • I believe that you're trying to access the element before it's even exist. – Ofir Baruch Jan 15 '21 at 09:28
  • Because that's run before the component gets rendered for the first time, but what are you actually trying to achieve? – jonrsharpe Jan 15 '21 at 09:28
  • Because the h1 element doesn't exist yet when that line runs. You're using React, so you need to use a Ref. However chances are your entire approach is wrong; with React you rarely manipulate the DOM directly, if ever. –  Jan 15 '21 at 09:29
  • Does this answer your question? [Using document.querySelector in React? Should I use refs instead? How?](https://stackoverflow.com/questions/59198952/using-document-queryselector-in-react-should-i-use-refs-instead-how) – t3__rry Jan 15 '21 at 09:33

1 Answers1

0

To get a reference to an element in React, you can use the useRef hook.

function Home() {
  const titleRef = React.useRef(null);

  React.useLayoutEffect(() => {
     console.log(titleRef.current);
  }, []);

  return (
      <div>
        <h1 ref={titleRef}>Pouet</h1>
      </div>
  );
}

Reference: https://reactjs.org/docs/hooks-reference.html#useref

ljbc1994
  • 2,044
  • 11
  • 13
  • Well, what I understand is it's not a good practice to use vanilla Js in React App. I use to work on React or JavaScript separated but not all together. So better do either a HTMLL CSS and Javascript website OR a react app ? – Antoine Bottin Jan 15 '21 at 09:51
  • It all depends on what your requirements are, as I've shown above, there are ways of getting access to DOM elements in React, but in terms of which approach you want to pursue is dependent on why you want access to the dom element? – ljbc1994 Jan 15 '21 at 10:00