Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i reusable function with boolean state in class component

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 ??

like image 952
FarhatDje Avatar asked Dec 28 '25 16:12

FarhatDje


1 Answers

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)

like image 120
CertainPerformance Avatar answered Dec 30 '25 04:12

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!