How can I single out which item in my map function should be affected by my function call in react?

Viewed 58

I have a series of sliders in a page and I have a specific requirement that requires to add a padding to the slider when there are no items below its 0 index. I have this done already, but I can't figure out how to make this function affect only the slider that I am clicking in. Right now, it affects all the sliders in my map function.

I am using react-elastic-carousel and I am targeting specified props, so the functions look like this

const onPrevStart = (prevItemObject, nextItemObject) => {
  if (nextItemObject?.index === 0) {
    setFirst(true);
  }
};

const onNextStart = (prevItemObject, nextItemObject) => {
  if (nextItemObject?.index !== 0) {
    setFirst(false);
  }
};

then I am calling it in a my map function in the JSX like this

<div className="App">

  {items.map((item, index) => (
    <div 
      key={index} 
      className="carousel-wrapper" 
      style={{ backgroundColor: "maroon" }}>
      <div>
        <Carousel
          breakPoints={breakPoints}
          renderArrow={renderArrows} //see the codesandbox to see these
          onPrevStart={onPrevStart} //here
          onNextStart={onNextStart} //and here
          style={{ backgroundColor: "white" }}>

          {item.itemdata.map((slide, index) => (
            <Item key={index}>{slide}</Item>
          ))}

        </Carousel>
      </div>
    </div>
  ))}
</div>

If you look in my codesandbox that I've made for you to play around with, you can test the functionality and see what I mean.

Thank you in advanced

1 Answers

I would say in order to control each slider individually, you need to break up your App component into smaller peaces.

My suggestion is to extract all custom logic for your slider to separate component, let's call it CustomSliderComponent and pass some data peaces from App to that child component. For example we can pass data, some other params like breakPoints as well as flags hasDynamicPadding.

Using those params we can have more tailored CustomSliderComponent component logic for your needs and then parent App component will only orchestrate and render each slider instance individually, where state is not shared but incapsulated inside each custom slider.

Codesandox example.

Related