Reputation: 483
In my react.js application, I have the following dialog:
<Dialog open={this.state.dialogIsOpen} onClose = {this.closeDialog} >
<DialogTitle id="simple-dialog-title">Create New Test User</DialogTitle>
<DialogContent>
<Grid container>
<Grid item xs = "6">
<label htmlFor = "id">Id: </label>
</Grid>
<Grid item xs = "6">
<input id = "id" value = {this.state.id}></input>
</Grid>
<Grid item xs = "6">
<label htmlFor = "name">Name: </label>
</Grid>
<Grid item xs = "6">
<input id = "name" value = {this.state.name}></input>
</Grid>
<Grid item xs = "6">
<label htmlFor = "email">Email:</label>
</Grid>
<Grid item xs = "6">
<input id = "email" value = {this.state.email}></input>
</Grid>
</Grid>
<button onClick = {this.createUser}>OK</button>
</DialogContent>
</Dialog>
The button at the bottom calls the following function:
createUser()
{
alert(this.state.email);
alert(this.state.users.length);
var newUser = {
id: this.state.id,
name: this.state.name,
emailAddress: this.state.email
}
this.state.users.push(newUser);
this.closeDialog();
}
When the createUser function is called, this.state.email, name, and id are undefined. However, this.state.users is the array that I expect it to be. It appears that the inputs are not binding correctly to the state values. Is there something special I need to do to bind inputs within a dialog?
Upvotes: 1
Views: 171
Reputation: 483
I found the solution:
I had to create an onChange handler for each input to send data changes back into the model when the user typed in the inputs. I found that here
I had to make the onchange handler generic as documented here
Upvotes: 1
Reputation: 5937
You shouldn't mutate state variables other than using setState
try this instead:
this.setState({
users: [...users, newUser]
})
instead of calling this.state.users.push(newUser)
Upvotes: 1