I have these multiple button components and one state isYes
. I want to handle the states such that clicking on one button component will trigger applyMethod
and the state for all buttons will be toggled. (i.e for button which was clicked other buttons whose state was previously set to true)
That is: only one button can have isYes
as true
at a time. Others should be set back to false. Only one button can have "Hello" text, others should be to default "Bye"
Right now, it only toggles state for the button that was clicked.
const [isYes, setIsYes] = useState(false);
const applyMethod = () => {
setYes(!isYes);
};
<Button onClick={applyMethod}>
<div>
isYes
? 'Hello'
: 'Bye'}
</div>
</Button>
CodePudding user response:
You can do a couple things, first thing you need to look at is your statrmanagemen pattern. Redux is a great way to pass data to multiple components.Theres a little setup but the rest of your code will be lighter and with react-redux hooks any component can access the data..
Now if your looking for an easier fix, you can setup views in your app. This is a component that basically handles all the state for this part a the app or feature. Then you can pass all props or state you like to your buttons
CodePudding user response:
You can use different state for each component, I don't think it is a good idea to use same state for multiple components (buttons). You can use an array to store states for different components and depending on each button click, you can update that and other button states accordingly.
I've taken 10 button as example in this case:
import React from "react";
export default function App() {
const btnCount = 10;
const btnsIntialState = new Array(btnCount);
btnsIntialState.fill(false);
btnsIntialState[0] = true;
const [btn, setBtn] = React.useState(btnsIntialState);
console.log(btnsIntialState);
const applyMethod = (index, value) => {
const btnCopy = [...btn];
btnCopy.fill(value);
btnCopy[index] = !value;
setBtn(btnCopy);
};
return (
<div className="App">
{btn.map((value, i) => (
<button onClick={() => applyMethod(i, value)} key={i}>
{value ? "Hello" : "Bye"}
</button>
))}
</div>
);
}