0

I am converting my HTML site to react and beneath the body tag, I have this script that toggles my mobile nav

    <script>
  window.addEventListener("scroll", function () {
    var nav = document.querySelector("nav");
    nav.classList.toggle("sticky", window.scrollY > 0);
  }, { capture: true });

  $(document).ready(function () {
    $('.fa-bars').click(function () {
      $('nav ul').toggleClass('active-2');
    })
  });
</script>

Then once I go to another page, the nav button stops working(i.e it won't toggle the nav until I refresh the page)

Please how can I fix that?

pj-c0d3r
  • 3
  • 5

1 Answers1

0

Perhaps you can put it in the componentDidMount method:

componentDidMount() {
    const script = document.createElement("script");
    script.src = "your-script-path";

    document.body.appendChild(script);
}

From the react documentation:

componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

https://reactjs.org/docs/react-component.html#componentdidmount

Ran Turner
  • 14,906
  • 5
  • 47
  • 53