Reputation: 979
I have the following form in React. What I want to do is send a POST request if the option from the select tag, is Participate.
<form action={this.props.action} method="POST" onSubmit={this.handleSubmit}>
<div className="ui action input">
<input type="text" placeholder="Enter code" name="code"/>
<select className="ui compact selection dropdown">
<option value="participate">Participate!</option>
<option value="check_status">Check status</option>
</select>
<button>
Submit
</button>
</div>
</form>
This is my handleSubmit function:
handleSubmit = (event) => {
event.preventDefault();
// HERE I want to check if the option as Participate, and then to the following code:
// Sudo code here
// IF STATEMENT event.target.value.option === 'participate'
const data = {id: this.state.code, is_winner: true};
fetch('/api/add_user', {
method: 'POST',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify(data),
})
.then(res => res.json());
// ElSE
// DO NOT SOMETHING ELSE (NOT POST)
};
Upvotes: 1
Views: 445
Reputation: 4055
To do it the 'React' way you'll want to capture the select box onChange event:
<select onChange={e=>this.setState({selectedOption:e.target.value})} className="ui compact selection dropdown">
Then your condition check will be something like:
if (this.state.selectedOption === 'participate') {...
Upvotes: 1
Reputation: 96
First I'd recommend you to assign a name attribute to your select
element like this
<select name="my-dropdown" className="ui compact selection dropdown">
Then inside your handleEvent method you can access the values in your form
const elementRef = Array.from(event.target.elements).find(
e => e.name === "my-dropdown"
);
// Here is the value from your dropdown selection
// that you can use to perform requests
console.log("Selection Value", elementRef.value);
Upvotes: 1