Reputation: 43
How to track changes if the value of the input field is already there. Probably it will be necessary to make the button active
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value="John" />
</label>
<input type="submit" value="send" />
</form>
);
}
}
Upvotes: 3
Views: 75
Reputation: 9769
Don't define value like value="John"
because it's not dynamic. you won't be able to change. so better to define your default value in state like this- this.state = {name: 'John'}
.
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {name: 'John', isChanged: false };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({name: event.target.value, isChanged: true});
}
handleSubmit=e=>{
e.preventDefault();
console.log(this.state)
}
render() {
const {name, isChanged} = this.state;
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={this.handleChange}/>
</label>
{ isChanged && <input type="submit" value="send" /> }
</form>
);
}
}
Hide submit button after submission-https://codesandbox.io/s/form-t00t4
Edit: Keeping the state of whether input is touched or not in ischanged.
Upvotes: 3