I'm quite new to react, and I have made a program with several buttons which need to be enabled one by one, when another button is clicked. Whenever I manually change the array values from true to false, the buttons show up, but not when I run a function which links to another button.
Array and enableObject function:
var counter = 0;
var disabledArray = [true, true, true, true, true, true, true, true];
function enableObject() {
disabledArray[counter] = false;
counter
}
Button which enables other buttons:
<Button Button variant="outlined" color="primary" type="submit" onClick={enableObject}>Add a new financial object</Button>
Example of a button which needs to be enabled:
<Button Button variant="contained" color="primary" type="submit" onClick={() => setButtonPopup(true)} disabled={disabledArray[0]}>
Object 1
</Button>
I just don't quite understand if I need to make another array, or what exactly to do to this to make it work. I mean, the array can't exactly be edited by the program itself, right? I just don't see any other workaround to this.
P.S. I'm using Material-UI, so don't get confused with the buttons and etc.
CodePudding user response:
First and foremost you are not using React-States. States are important because changing them forces a new render. You need this so the state of your button (enabled / disabled) changes. Without a new render your button(s) just stay disabled.
When using React States you should treat them as immutable. So if you change your array in the state variable you would need to create a new array. Otherwise react doesn't notice the state change and you'll have the same problem again.
Here's a simple example solution using functional-style react for what you're trying to do:
function Example() {
const [counter, setCounter] = useState(0);
const [disabledArray, setDisabledArray] = useState([true, true, true, true, true, true, true, true]);
function enableObject() {
const clone = [...disabledArray];
clone[counter] = false;
setDisabledArray(clone);
setCounter(counter );
}
}
CodePudding user response:
Using state to hold your array of booleans will allow you to update the dom when changing it. Since you're already updating state through the array, there's no need to do it for counter, as it'd just be twice the calls to state. It's therefore still a normal variable.
If done through class component, I'd put both of them in state.
const Component = () => {
const [array, updateArray] = useState([true, true, true, true, true, true, true, true]);
let counter = 0;
const enableObject = () => {
const tmpArray = array
counter
tmpArray[counter] = false
updateArray(tmpArray)
}
return (
<React.Fragment>
<Button Button variant="outlined" color="primary" type="submit" onClick={enableObject}>Add a new financial object</Button>
{array.map((isDisabled) => {
return (
<Button Button variant="contained" color="primary" type="submit" onClick={() => setButtonPopup(true)} disabled={isDisabled}>
Object 1
</Button>
)
})}
</React.Fragment>
)
}