era s'q
era s'q

Reputation: 591

Check if an element is in center in React

I'm implementing a carousel and I want to target the element at the center of the slider. So, I can make it pop a little. enter image description here

How can I target this component? I have found ways to know if the element is inside the viewport or not but I want to know if it's horizontally centered.

Original Problem

Upvotes: 1

Views: 1763

Answers (1)

Joe Lloyd
Joe Lloyd

Reputation: 22453

Horizontal scroll and set state

Since you have no code my answer will be more theoretically how to do it. So first off you should have a boolean state that you can toggle for the active state. This state should be controlled by the container. That way you can only activate one at a time.

Next you should get 2 values, the X scroll position of the container and the center point of the visible area of the gallery.

Then you can just calculate an offset on mount and then X scroll of the gallery.

So in theory it starts at 0 and your container is 500px you know that the active slide is at the 250px mark so you can calculate that with the position of the slide, it should be the last slide that passed that point. then just recalculate this value on scroll. (maybe throttle)

Possibly able to use react-hook-inview

I've used this react hook before on the Y axis. I'm not 100% sure that it works on the X scroll. But it can be a great way to trigger a state change on each of the slides. The only issue is that you'll be adding a event listener to each of your slides (possible performance hit).

You can see that lib here

This one lets each slide control it's own inView state.

Upvotes: 1

Related Questions