React – When checked, the old condition is retained

I had an incomprehensible problem just a few days ago, I asked a question related to getting an index of values enter link description here I got a reliable answer and everything worked well for me after I slightly changed my existing code.

When I click on a certain block, it is highlighted in blue (this is how it should be), but the problem is that after clicking on another block, the old color from the block does not disappear, it looks like this

enter image description here

As you can see, after clicking on a new block from the old color does not disappear, how to solve this problem?

SelectColorsTheme.js

export default function SelectColorsTheme(props) {
    const rows = SideBarColors.map(function (col, index) {
        
        return <SelectThemeContent {...props} col={col} key={index} index={index}/>
    }).reduce(// code) {
        // code
    });
    return <div className="container">{rows}</div>;
};

SelectThemeContent.jsx

export default function SelectThemeContent(props) {

    const { col, index } = props;

    const [selectedIndex, setSelectedIndex] = useState(false);

    const setBorder = (index) => {
        setSelectedIndex(index);
    };

    const selectBorder = classNames({
        'builtin_theme_preview': true,
        'selectBorder': index === selectedIndex ? 'selectBorder' : null
    });

    return (
        <div className={selectBorder} key={index} onClick={() => props.SideBarPageContent(col) || setBorder(index)}>
// code
</div>

Answer

Assuming you want only one item being selected, you need to lift state up from SelectThemeContent to SelectColorsTheme. Currently each child has its own state that knows nothing about the siblings.

So this code must be in SelectColorsTheme

const [selectedIndex, setSelectedIndex] = useState(false);

const setBorder = (index) => {
    setSelectedIndex(index);
};

Then pass setBorder function in props from SelectColorsTheme down to SelectThemeContent:

return <SelectThemeContent {...props} col={col} key={index} index={index} setBorder={setBorder}/>

And replace the handler in SelectThemeContent:

onClick={() => props.SideBarPageContent(col) || props.setBorder(index)}

Leave a Reply

Your email address will not be published. Required fields are marked *