How to implement and onScroll event or any other event on a component?

What would be the proper way to implement and onScroll even on a component? Or any other even for that matter. All the solutions that I’ve found for react don’t seem to work in frontity. For example in react its recommend to attach events in the componentDidMount(){} but that doesn’t seem how frontity runs things. Any suggestions?

Hey @f4b13l90

Its hard to give you any advice without some code. :sweat_smile:
Can you provide the code you have tried to create a onScroll method inside Frontity?

Kind regards
Chris

1 Like

Yeah I didn’t even know where to start. I did find a solution that seems to work .
I wanted to implement a simple fixed header when the user scrolls. And I was having difficulty adding the script in jsx. I’m still pretty new using react :frowning: . Any insight would be highly appreciated. Meanwhile this is my solution…
{(()=>{if (typeof window !== “undefined”) {
// browser code
// When the user scrolls the page, execute myFunction
window.onscroll = function() {myFunction()};

    // Get the header
    var header = document.getElementById("myHeader");

    // Get the offset position of the navbar
    var sticky = header.offsetTop;

    // Add the sticky class to the header when you reach its scroll position. Remove "sticky" when you leave the scroll position
    function myFunction() {
      if (window.pageYOffset > sticky) {
        header.classList.add("sticky");
        document.body.style.paddingTop="100px";
      } else {
        header.classList.remove("sticky");
        document.body.style.paddingTop="0px"
      }
    }
    }})()}</script>

Hi @f4b13l90,

I think that solution will work, but all you did there is working past React.

A simple solution using React hooks

I hope that helps.

Kind regards
Chris

Hi @f4b13l90

Frontity is “isomorphic”. This means that the same JavaScript code runs both on the server (for SSR) and on the client. The window and document objects don’t exist server-side, only in the browser, so simply referencing them in your code could cause you problems.

Frontity provides “actions” that you can hook into. Some of these actions run on the server and some on the client - and some run on both server and client. If you only want code to run on the browser then you can hook that code into an action that runs on the client.

See this page in our docs for more info. You will probably want to use afterCSR.

Another option to run code client-side is to use a useEffect React hook. See this post for a more detailed answer to a similar question.