Is there a way for a property in the React state object to refer to it's own properties? Like in the example below:
this.state = {
currentTotal: 30,
columnLength: Math.ceil(this.currentTotal / 3), // Getting NaN.
}
Is there a way for a property in the React state object to refer to it's own properties? Like in the example below:
this.state = {
currentTotal: 30,
columnLength: Math.ceil(this.currentTotal / 3), // Getting NaN.
}
The issue here is that this.currentTotal
is undefined, which will result in a NaN during this arithmetic: this.currentTotal / 3
.
There are a few ways to resolve this, but the perhaps the simplest solution is to just defer the Math.ceil(this.currentTotal / 3)
calculation til after your components state
is fully initialised like so:
class Component {
constructor() {
const state = {
currentTotal: 30,
columnLength: 0
}
// Defer calculation til after state has been initialised
state.columnLength = Math.ceil(state.currentTotal / 3)
// Assign your initialised to the component
this.state = state
console.log( this.state.columnLength )
}
}
new Component()
since you already need a currentTotal, I think this solution would be the most elegant
constructor() {
const currentTotal = 30; // initialization
this.state = {
currentTotal,
columnLength: Math.ceil(currentTotal / 3),
}
}
We do usually to implement switch.
this.setState({ isOpen:!this.state.isOpen });
Mutate state using setState only.