panelsnap icon indicating copy to clipboard operation
panelsnap copied to clipboard

I can't get PanelSnap to work in react

Open Drakarta opened this issue 3 years ago • 6 comments

The console isn't giving me any errors either, but it's just not snapping. Do you mind helping me?

https://github.com/Drakarta/portfolio

Drakarta avatar Oct 07 '22 10:10 Drakarta

Hey hey,

I can't view that repository it seems. Have you set that to private?

Have you tried the React demo in the docs folder?

guidobouman avatar Oct 15 '22 15:10 guidobouman

oops i was messing with github im still kinda new to using github, but here's the new repo https://github.com/Drakarta/Portfolio-Website/tree/panelsnap

and yes i tried the react demo but it's using a class component instead of a functional one and im getting some weird errors which i dont really understand.

thank you for your time!

Drakarta avatar Oct 19 '22 09:10 Drakarta

@Drakarta The issue was probably cause because React uses Strict Mode by default, and that means that your useEffect would run the panelsnap initialization code twice, causing some issues. Here is an example of using panelsnap with functional components in react: https://codesandbox.io/p/devbox/kcndzk?file=%2Fsrc%2FApp.jsx

aleksei-stukalov avatar Feb 04 '24 10:02 aleksei-stukalov

Ah, makes sense, I should update the demo to use React 18 & functional components by now.

Thanks for the reply @yUtopist, much appreciated!

guidobouman avatar Feb 04 '24 11:02 guidobouman

@guidobouman I can help you with that. I am working on a small NextJS Project and that thing adds up whole another layer of issues in Next, but it is quite common with libraries that require DOM on load. So the simple trick wrapping up the PanelSnap init inside a checker will do the trick like so:

useEffect(() => {
  if (typeof window !== 'undefined') {
    const panelSnap = new PanelSnap({
      container: document.body,
      panelSelector: '> section',
    });
  }
});

So without the typeof window !== 'undefined' conditional - code runs before document.body is created.. or something like that..

Thank you for an awesome library by the way. css scroll snap is still broken and is very unreliable to cross browser, but your library is magic!

aleksei-stukalov avatar Feb 05 '24 08:02 aleksei-stukalov

I have long moved on from this project haha, but yes it was an issue with strict mode 🫡

Drakarta avatar Feb 05 '24 08:02 Drakarta