React - change button according to useState change on parent component

Viewed 40

I am struggling with this situation:

const MyComponent = () => {
    const [activePanel, setActivePanel] = useState("buttonAAA");


 return <>
...
 <GroupOfButtons
     onClickFunction={(buttonId) => setActivePanel(buttonId)}
     buttonsList={[
        { text: "AAA", id: "buttonAAA" }, 
        { text: "BBB", id: "buttonBBB" }, 
        { text: "CCC", id: "buttonCCC" }]}
 />
...
<span onClick={() => setActiveOrderDetailsPanel('buttonBBB')}>buttonBBB</span>
...

{activePanel === "buttonAAA" && <p>xxxx</p>}
{activePanel === "buttonBBB" && <p>yyyy</p>}
{activePanel === "buttonCCC" && <p>zzzz</p>}


}

And here is the GroupOfButtons component: import { useEffect, useState } from 'react';

const GroupOfButtons = ({ buttonsList, onClickFunction }) => {
    const [condition, setCondition] = useState(0);

    const handleOnClick = (index, id) => {
        setCondition(index)   
        onClickFunction(id)
    }
    

    return buttonsList.map((button, index) => (
        <button
            key={index}
            className={`standard-button ${condition === index ? "active-button" : "inactive-button"} ${className ? className : ""}`}
            onClick={() => handleOnClick(index, button.id)}
        >
            {button.text}
        </button>
    ));
}

I made it work fine. So... if I click a button rendered by this component, the one clicked gets highlighted by className.

However, those buttons are not real Links I can manage via Router.

The problem is that in MyComponent there is another button below in the page, which is called buttonBBB - this button changes the useState. And the right panel shows UP. The problem is that the GroupOfButtons is not reading the useState state - it just sets a new state when clicked.

How can I edit the code, to make the Span buttonBBB change also the color of the button rendered by the GroupOfButtons component?

export default ButtonGroup;

1 Answers

You can create a true false value for your state buttons. Then, click the buttons you want active.

className={this.state.buttonAAA === true ? 'active' : ''}
Related