javascriptreactjsfrontendoverscroll

React: add className="active" to list item after horizontal scroll (css: overflow-x: scroll;)


I wish to update my className on my list items based on my horizontal scrolling behavior on a Slider in React. Any suggestions on how I could solve this? I could not find a solution so far.

Currently, one image fills up the whole width of the window and upon scrolling the next item becomes visible. But I also want to make this switch visible in the ul list item. Basically, after scrolling, I want that the className from the list item 1 becomes "inactive" and the second list items className becomes "active" and so on.

Basically the main component looks something like this:

import React, { Component } from 'react';
import Slider from './Slider';

export default class Property extends Component {

  constructor(props) {
    super(props);
    this.state = {
      object: [
        {
          title: "...",
          description: "...",
          img: "...",
        },
        {
          ...}
      ]
    };
  }

  render() {
    return (
      <div id="property">
        <div className="detailsWrapper">
          <h2>Lodge Highlights</h2>
          <Slider object={this.state.object}/>
          <ul>
            <li className="is-active"></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
          </ul>
        </div>
      </div>
    )
  }
}

My Slider component looks like this:

import React, { Component } from 'react';

export default class Slider extends Component {

  render() {
    return (
      <div className="higlights_slider">
        {this.props.object.map((eachObject, index) => {
          return (
            <div className="highlights_slider_content" key={eachObject.id} value={eachObject.id}>
              <img src={eachObject.img} alt=""/>
              <h3>{eachObject.title}</h3>
              <h4>{eachObject.description}</h4>   
            </div>
            )
           })}
        </div>
    )
  }
}

And in my css (or scss) I use for .highlights_slider overflow-x: scroll

Any help is appreciated! Thanks in advance!!


Solution

  • you only need one class. The observer will inform you every time a slider passes the threshold, so you can remove the class from the slide at current index - 1 and add the class on the current slide.