Adding id to element on scroll using react hooks useInView and useID in nextjs.13
Right ... so the title might be a bit daunting, but I think this is actually just some plain JS at the end of it. But I'm stuck here now ...
In this code you see two react hooks, useInView and useID, being used to listen for scroll behaviour and adding an id to an element:
... this is not all of the code. The entire react component can be seen here:
https://github.com/AMarlonG/Website/blob/main/web-app/PageComponents/FrontPage.tsx
12 Replies
Now, what I want is:
When elementIsVisible equals true, I want the newId to be added to the element. When elementIsVisible equals false, I want neId to be removed from the element.
In other words – when
.shallWeWorkContent
is visible, I want .mainInfoContent
to get an id attribute from newId.
I've tried using this video to solve it, but I'm banging my head against the wall here. Do I have to use an if statement or not?
https://www.youtube.com/watch?v=V-CBdlfCPicI've made the elementIsVisible work correctly:


And the useId is adding a (weird looking) id attribute to the element I want:

useId
generates a unique id, which is where that's coming fromYep! I know, and I used a while to make it work, but what's the solution to the big question. You know?
Just to clarify, you want
.mainInfoContent
to only get the newId
if elementIsVisible
, right?
If so, you can probably just do something like <div id={elementIsVisible ? newId : ''} className={styles.mainInfoContent}>
Jeez! That was easy! I was trying several different if statements and got nowhere ...
Haha! I love how JS sometimes is so simple!
... follow up question: in the useId docs I can't find out how to make a custom id, and not that weird looking number.
https://react.dev/reference/react/useId
It would be good to have an id name that is more logical like
scrolling
or whatever ...The solution is just to not use
useId
I think lollll
I'd actually never heard of that hook until today
something like this then: <div id={elementIsVisible ? 'scrolling' : ''} className={styles.mainInfoContent}>
You're friggin kidding me!!!!
Hahahahahahahhaha!!!!
This is the smoothest way I've seen on the internet to ad an attribute ... I've been googling for days, and it's this simple!
I always give out a peacock to the best answer of the day, but you just earned a life supply of them!
:) glad i could help!
Thank you so much! Have a great day! 🫡