Tanvir Ahamed
Tanvir Ahamed

Reputation: 1

How can I get current displayed div id in react?

when the user scrolls the screen, I need to know the currently displayed div id to set the div key selected.

    <button
        type="button"
//here, I want to access current displayed div id
// I need to add some css class based on current displayed div id
className={`header_link ${
current_displayed_div_id === "Video" ? "selected" : "" // here I need to check
}`}
onClick={() => {
scrollTo(videoRef.current);
}}
>
Price
</button>

//here is my div using creatRef
<div
        className="section"
        height:
        id="Video"
        ref={videoRef} style={{ "auto" }}
>
<div>
    <div className="nav-item">
                        <span className="nav-link">
                          <i className="icofont icofont-contacts"></i>
                            {translate("video")}
                       </span>
        <div className="material-border"></div>
    </div>
</div>
<div className="mt-4 text-center">
    <div className="embed-responsive embed-responsive-16by9">
        <iframe
                src={this.props.datatab.video}
                title="video"
        >
        </iframe>
    </div>
</div>
</div>

when user scrolls the screen, I need to know the currently displayed div id to set the div key selected.

Upvotes: 0

Views: 2226

Answers (1)

ourmaninamsterdam
ourmaninamsterdam

Reputation: 2452

You could use the browser's native Intersection Observer API to track if an element is on screen and integrate this into your React component setup. Or you could use a React library like https://github.com/researchgate/react-intersection-observer or https://github.com/fkhadra/react-on-screen which should work out of the box.

Upvotes: 1

Related Questions