Sylwia Makuch
Sylwia Makuch

Reputation: 117

Selecting 1 Index from a Mapped array

I am trying to build a Sound Board. I'm having a hard time understanding how to select one index to change my button's colour as currently it is changing all the buttons, but I want to change only one.

$isActive is passed above in a styled comp like this :

const Button = styled.button<{ $isActive?: boolean }>
background: ${props => props.$isActive ? "linear-gradient(55deg, #ff00e1, #ffb9df,#ffb9df, #ff00cc);" : "black"};
export default function BassPlayer() {
    const [activeSound, setActiveSound] = useState(null);
    const [activeIndex, setActiveIndex] = useState(null);
    const [isActive, SetIsActive] =useState(false); 
    const createSound = (beat: string) => {
        return new Howl({
            src: beat,
            autoplay: false,
            loop: false,
            volume: 0.5
        });
    }
    const handleClick = (beat: string, index: number ) => {
    const ButtonColorChange = SetIsActive(!isActive);
        if (activeSound) {
            activeSound.stop(); 
        }
        if (activeIndex !== index) {
            const newSound = createSound(beat);
            newSound.play();
            setActiveSound(newSound);
        }
        setActiveIndex(index);
    };
    return (
        <Container>
            <Title>Bass</Title>
            <Grid>
                {
                    bassData.map((beat, index: number) => {
                        return <Button key={index} $isActive={isActive} onClick={() => handleClick(beat.src,index)}>{beat.title}</Button>
                    })
                }
            </Grid>
        </Container>
    )
};

Upvotes: 0

Views: 129

Answers (1)

Dave
Dave

Reputation: 7717

SetIsActive does not return a value, so ButtonColorChange will be undefined. If you set IsActive to the index that's active, then later you can compare the index of the baseData.map to the isActive index and when they match - that's the button to hilight.

// change this
const ButtonColorChange = SetIsActive(!isActive);

// to this
SetIsActive(index);

// ... then change this
return <Button key={index} $isActive={isActive} onClick={() => handleClick(beat.src,index)}>{beat.title}</Button>

// to this
return <Button key={index} $isActive={index === isActive} onClick={() => handleClick(beat.src,index)}>{beat.title}</Button>

Upvotes: 1

Related Questions