user1177860 user1177860 - 2 days ago 4
React JSX Question

Loop through react to set state

I have a event Handler in react to set the state on 10 items, what is the best way to set this out with out repeat this.state.

handleOpacityThermatic(event) {
if (event == 0.1) { this.setState({ opacityValue: 0.1, opacityName: '10%' }); }
if (event == 0.2) { this.setState({ opacityValue: 0.2, opacityName: '20%' }); }
if (event == 0.3) { this.setState({ opacityValue: 0.3, opacityName: '30%' }); }
if (event == 0.4) { this.setState({ opacityValue: 0.4, opacityName: '40%' }); }
if (event == 0.5) { this.setState({ opacityValue: 0.5, opacityName: '50%' }); }
if (event == 0.6) { this.setState({ opacityValue: 0.6, opacityName: '60%' }); }
if (event == 0.7) { this.setState({ opacityValue: 0.7, opacityName: '70%' }); }
if (event == 0.8) { this.setState({ opacityValue: 0.8, opacityName: '80%' }); }
if (event == 0.9) { this.setState({ opacityValue: 0.9, opacityName: '90%' }); }
if (event == 1.0) { this.setState({ opacityValue: 1.0, opacityName: '100%' }); }

},


for loop it?

for (let i = 1; i <= 10; i++) {
}

Answer

Maybe like this:

handleOpacityThermatic(event) {
    const values = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0];

    values.forEach((val) => {
        if (event === val) {
            this.setState({
                opacityValue: val,
                opacityName: `${val * 10}%`
            })
        }
    })
}
Comments