top of page
Logo der Online Agentur mdwp

Controlled component

A controlled component in React Js is a component that controls the values of input fields within its own state. What this means is that instead of the input field maintaining its own internal state, the state for that field is held and controlled by the React component. Usually, the values of the input fields are updated in the state using event handlers like onChange. So the data flow becomes one-way (also called unidirectional data flow) which makes the application more predictable and easier to debug because only a specific component controls the state and updates it.

Here's a basic example of a controlled component in React:

```javascript
class ControlledForm 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});
}

handleSubmit(event) {
alert('A name 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(
<ControlledForm />,
document.getElementById('root')
);
```

This code demonstrates a controlled form with a single input. We are controlling the input value state by updating it with the `handleChange` function using `this.setState({value: event.target.value});`, and the input field reflects the value of the state when it changes. We will also see the state value when we submit the form with `alert('A name was submitted: ' + this.state.value)`.

bottom of page