asdasd
asdasd

Reputation: 93

ReactJS, key property breaks CSS transition while adding class

When I'm adding key property to the following code it breaks my CSS transition by removing class 'active' after re-rendering. Without a key property everything works great, can somebody explain why this happens?

handleClick function is adding class 'active' on clicked element:

const handleClick = (e) => {
    const {currentTarget: btn} = e;
    const getAllActive = selAll('.btn-filter.active');

    setActiveFilter(getAllActive);
}

Component with onClick handler and key prop:

 <Splide options={{
    gap: '8px',
    perMove: 1,
}}>
    {_.map(taxonomyServiceData, ({name, id}) => {
        return (
            <SplideSlide key={_.uniqueId()}>
                <FilterButton onClick={(e) => {
                    handleClick(e);
                }} categoryId={id} buttonText={name}/>
            </SplideSlide>
        );
    })}
</Splide>

Thanks in advance!

Upvotes: 0

Views: 297

Answers (1)

gear4
gear4

Reputation: 844

This documentation describes exactly what the issue is: Lists and Keys


TLDR: Keys should be given to the elements inside the array to give the elements a stable identity, and the key needs to be exactly the same for the item as it was before. Using _.uniqueId() will wipe out any previous keys that existed so React will 100% rerender it.


Another major issue your code has: you should not modify classes outside React unless you have absolutely no access to the thing you're trying to modify.

This link describes how to set class names in React: FAQ: Styling

Upvotes: 1

Related Questions