javascriptreactjsqueryselector

document.querySelector is not working in my react component


function Slider() {
  const track=document.querySelector('.slide__track')//To access the div with class slide track
  console.log(track);
  return (
    <div className="slider">
      <i className="fas fa-chevron-left"></i>
      <div className="head">
        <h1 className="title">Based on your last search</h1>
        <h6>View more</h6>
      </div>
      <div className="slider_container">
        <ul className="slider__track">
          <li className="slider__items">
            <Card />
          </li>
        </ul>
      </div>
      <i className="fas fa-chevron-right"></i>
    </div>
  );
}

i cannot access the div with class slide__track. What is the problem here? Or how can i access that element?


Solution

  • Try and use this code in useEffect()

    useEffect(() => {
        const track = document.querySelector('.slide__track')
        // have access to it
    }, []);