This is not the duplicate of this, as i'm using controlled components and hence, it should have target.value . I'm getting this error following the example given here, I know that i am not binding onClick and onSubmit with 'this' , (the code works well on binding) but instead i have changed 'this.handleChange' to an arrow function '() => this.handleChange()' and similarly for handleSubmit. This should have worked as given here
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ""
};
}
handleChange(event) {
this.setState({
value: event.target.value
});
}
handleSubmit(event) {
alert("event was submitted" + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={() => this.handleSubmit()}>
<label>
Name:
<input
type="text"
value={this.state.value}
onChange={() => this.handleChange()}
/>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(<NameForm />, document.getElementById("root"));
this.setState({value: event.target.value})instead ofthis.setState({event.target.value})}afterrender, the issue @nrgwsth points out above, the;afterevent.target.valueinhandleChange... All of which your browser or IDE would have told you about. It's also useful to create a runnable example demonstrating the problem using Stack Snippets (the[<>]toolbar button). Stack Snippets support React, including JSX; here's how to do one.