About
This page is about the handling of input element in React.
Type
Controlled component
The react forms components input accept a value attribute that is used to implement a controlled component.
A React form:
- written as a class component
- where the state is controlled by React (ie Controlled component)
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'DEFAULT'};
// Mandatory binding of this.
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
// toUppercase to enforce it
console.log('handleChange was fired with the value '+event.target.value.toUpperCase());
this.setState({value: event.target.value.toUpperCase()});
}
handleSubmit(event) {
console.log('Your submitted name is: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<div>
<p>Submit your name. It will be always uppercase and for each keystroke, the value attribute will be updated.</p>
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
<div id="root"></div>
Uncontrolled Component
input example with a Uncontrolled Component using ref.
Note that in React, you define the default value with the attribute defaultValue and not value.
class NameForm extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
this.input = React.createRef();
}
handleChange(event) {
// Always uppercase :)
console.log('handleChange was fired with the value '+this.input.current.value);
this.input.current.value = this.input.current.value.toUpperCase();
}
handleSubmit(event) {
console.log('The ref gives access to the HTML element via current: ' + this.input.current.__proto__.toString());
console.log('where you have access to all HTML attribute such as the value');
console.log('Example: the name submitted was: ' + this.input.current.value );
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={this.input} defaultValue="ChangeMe" onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
<div id="root"></div>