1
votes

this is a carousel made using embla-react-carousel.

i want to add a certain id or classname of each object in array because i want to add some kind of a text for each dot navigation...

the reason why i use styled components because i don't know how to add selected class for sass.so, it's like i have to choose between each one.

this is how do i make it work but not in styled components.

    if (embla) {
    
    // console.log(embla.scrollSnapList)
    return embla.scrollSnapList().map((snap, index) => (
      

      // <ProgramTitle/>

            <button
                key={index}
                active={index === slide}
                aria-label={`Scroll to slide number ${index + 1}`}
                // aria-label={`Scroll to slide number ${index + 1}`}
                type="button"
        onClick={() => embla.scrollTo(index)}
        // className={`${button + index}`}
        className={`${button}`}
        id={`${button+"-"+index}`}
            >
        {/* <button className={hr}/> */}
      </button>
        ));
    }
    return "gagal";
}, [embla, slide]);

below is how do i do it right now which is not work

          {scrollSnaps.map((snap, index) => (
            <DotButton
              selected={index === selectedIndex}
              onClick={() => scrollTo(index)}
              key={index}
              id={`${button+"-"+index}`}
            />
          ))}
        </Dots>

and my styled components

  const Dot = styled.button`
  background-color: transparent;
  cursor: pointer;
  position: relative;
  padding: 0;
  width: 3rem;
  height: 3rem;
  margin-right: 0.75rem;
  margin-left: 0.75rem;
  border: 0;
  display: flex;
  align-items: center;

  &::after {
    border-top: 1.2px solid #414242;
    opacity: .5;
    content: "";

    ${({ selected }) =>
      selected &&
      ` 
        border-top: 1.2px solid #414242;
        opacity: 1;
      `}
  }
`;
export const DotButton = ({ selected, onClick,  someId}) => (
  <Dot selected={selected} onClick={onClick} id={someId}/>
);
1

1 Answers

0
votes

I'm not sure if I understand your issue. Do you want to add a dynamic className/id to your carousel items?

Then, in your loop try something like:

      {scrollSnaps.map((snap, index) => (
        <DotButton
          selected={index === selectedIndex}
          onClick={() => scrollTo(index)}
          key={index}
          id={`${button}-${index}`}
        />
      ))}

The example above will work if the variable button is defined. You may want to try something more dynamic like: id={`element-${index}`}

Take a look at your template literal. Curly braces are used to declare a variable inside backticks: {`${THIS_IS_A_VARIABLE}-THIS_IS_A_STRING`}.