Home > Net >  Change styling for single item in list ReactJS
Change styling for single item in list ReactJS

Time:09-06

I have an unsorted list with a few elements that gets generated by mapping through an array of items. The items are clickable and I already have a function to use the information of a clicked item. However I want to change the styling of the selected item to make it visible which one you have selected.

    function SelectableList({items, onItemSelected}: Props) {
    const [isSelected, setIsSelected] = useState(false);
    const handleToggle = () => {
        setIsSelected(!isSelected);
    };
    return (
        <div>
            <ul className={styles.ul}>
            {items.map((item, i) =>
                (
                    <li className={isSelected ? styles.selected : styles.li} key={item.id} onClick={() => {onItemSelected(item); handleToggle()}}>
                        <SelectableItem key={i} item={item} />
                    </li>
                )
            )}
            </ul>
        </div>
    );
}

The way I have done it however changes the styling of every item and not only the one selected.

Is there any way to make it work with the structure I have right now? Or do you maybe have a better solution in general?

CodePudding user response:

You have to check the condition with the unique Keys in li tag.

 function SelectableList({items, onItemSelected}: Props) {
    const [isSelected, setIsSelected] = useState(false);
    const handleToggle = (i) => {
        setIsSelected(i);
    };
    return (
        <div>
            <ul className={styles.ul}>
            {items.map((item, i) =>
                (
                   // checks the selectedItem with index
                    <li className={isSelected === i ? styles.selected : styles.li} key={item.id} onClick={() => {onItemSelected(item); handleToggle(i)}}>
                        <SelectableItem key={i} item={item} />
                    </li>
                )
            )}
            </ul>
        </div>
    );
}
  • Related