Normally in HTML you do something like this:
<form>
<input type="text"/>
<input type="text"/>
<input type="submit"/>
</form>
I believe this is not the React way to do it.
Another way to do like i did in my app, is not the best way to do as well i believe. Like this:
buttonclickRequest(){
var reasonn = document.getElementById("testControl").value;
}
<div>
<FormControl id="testControl"/>
<Button id="btnRequest" onClick={this.buttonclickRequest}/>
</div>
In other stackoverflow topics I saw examples like this:
constructor(props) {
super(props);
this.state = {
firstName: '',
lastName: '',
place: '',
address: '',
email: '',
phoneNumber: ''
};
}
handleClick() {
//do something
}
handleChange = (e) => {
this.setState({
[e.target.id]: e.target.value
})
}
<div>
<input type="text" onChange={e => this.handleChange(e)}/>
<button type="submit" onClick={this.handleClick}/>
</div>
But i have my questions at this point as well,
I don't know how to do this properly with multiple text inputs:
You can make multiple specific changehandlers which is inefficiënt,
You can make a changehandler with a switch to set the properties
Is it even efficient to do a handle change on the inputfields? Because I just want the inputfield values when the button is clicked..
This is the form I'm talking about.
So how to properly get the multiple input data with React, when the button is clicked?
Thanks for your help in advance!
I think first you should add name
attribute to your input field and use the name to set the state and then use the state on handleClick
:
constructor(props) {
super(props);
this.state = {
firstName: '',
lastName: '',
place: '',
address: '',
email: '',
phoneNumber: ''
};
}
handleClick = () => {
//do something
console.log(this.state);
// should be something like this {
// firstName: '',
// lastName: '',
// place: '',
// address: '',
// email: '',
// phoneNumber: ''
//}
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
render() {
return(
<div>
<input type="text" name="firstName" onChange={this.handleChange}/>
<input type="text" name="lastName" onChange={this.handleChange}/>
<button type="submit" onClick={this.handleClick}/>
</div>
)
}
Note that the name should match the state key.