i have 5 state with 5 function too.. the state value is
imgError: false, imgError2: false, imgError3: false, imgError4: false, imgError5: false,
and the function is
const erroImg = () => {
this.setState({
imgError: true,
})
}
const erroImg2 = () => {
this.setState({
imgError2: true,
})
}
const erroImg3 = () => {
this.setState({
imgError3: true,
})
}
const erroImg4 = () => {
this.setState({
imgError4: true,
})
}
const erroImg5 = () => {
this.setState({
imgError5: true,
})
console.log('tes')
}
the question is,, how can i use one function for change the five state ??
Use an array for the imgErrors in state instead, and make a function that returns a function that changes the appropriate index:
this.state = {
imgErrors: new Array(5).fill(false)
};
const errorImg = (i) => () => {
this.setState({
imgErrors: this.state.imgErrors.map(
(val, j) => j === i ? true : val
)
});
};
Then, for example, instead of
onerror={erroImg3}
you could do
onerror={errorImg(2)}
(keeping in mind the zero-indexed arrays)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With