I am trying to increment the react state counter based on some option selection from the dropdown menu. The problem is I want to preserve the counter value and continuously increment based on condition like option "Test"
is selected.
I am using below code to increment a counter if "Test"
is selected in both the dropdown
{this.state.DownloadPrepare == "Test" ? this.state.Identify == "Test" : this.state.CalcNoOfObs+1}
You're probably looking for something like this: https://codesandbox.io/s/zealous-shirley-flznm
class App extends React.Component {
state = {
counter: 0,
listOne: null,
listTwo: null
};
incrementIfTest = event => {
console.log(event.target.name);
if (
//check if is already selected, do not want to double count
event.target.value === "Test" &&
this.state[event.target.name] !== "Test"
) {
//increment count
this.setState({
...this.state,
counter: this.state.counter + 1,
[event.target.name]: event.target.value
});
//decrease count if they remove Test selection, cannot be below 0.
} else if(this.state[event.target.name] === "Test"){
this.setState({
...this.state,
counter: this.state.counter > 0 ? this.state.counter - 1 : 0,
[event.target.name]: event.target.value
});
}
};
render() {
return (
<div>
<h4>{this.state.counter}</h4>
<select name="listOne" onChange={this.incrementIfTest}>
<option />
<option>DownloadPrepare</option>
<option>Test</option>
</select>
<select name="listTwo" onChange={this.incrementIfTest}>
<option />
<option>DownloadPrepare</option>
<option>Test</option>
</select>
</div>
);
}
}
Make use of the onChange()
event-listener on the Dropdown (select tag). We can pass in the event and have access to the selected option through event.target.value
. If it equals Test
, we just increment the count
I made a script for on click you can do on the change as well I hope It's useful for you.
Thanks
constructor(props) {
super(props);
this.state = {
DownloadPrepare: "Test",
Identify: "",
CalcNoOfObs: 0
};
}
click() { // make your function what you want on change
this.state.DownloadPrepare == "Test"
? this.setState({
Identify: "Test"
})
: this.setState({
CalcNoOfObs: this.state.CalcNoOfObs + 1
});
}
<button onClick={() => this.click()}>click</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.