Controlled Components in React | Develandoo | Blog

Controlled Components in React

React, as it is, has two types of forms manipulation, with the help of controlled components and uncontrolled components.

Today we are going to cover basic ideas of how to work with controlled components. A form component with a value or checked prop is called a controlled component. In a controlled component, the value rendered inside the element will always reflect the value of the prop. By default the user won’t be able to change it.

Lets see an example of how this works, start with a Search component that contains an input field:

This will render a form field displaying an immutable value of “React”. Any user input will have no effect on the rendered element because React has declared the value to be “React”.

To be able to make this value change, you need to handle it as a component state. This way, any changes to the state value will be reflected in the interface.

You could even give the end user the ability to update the state value using the onChange event.

This may look like a convoluted way to deal with forms, but it has the following advantages:

It stays true to React way of handling components. The state is kept out of the interface, and is entirely managed in your Javascript code. This pattern makes it easy to implement interfaces that respond to or validate user interactions. For example, you could very easily limit the user input to 50 characters:

Special Cases

There are a few special cases to remember when creating controlled form components: TextArea and Select.

TextArea

In HTML, the value of “<textarea>” is usually set using its children:

For HTML, this easily allows developers to supply multiline values. However, since React is javascript, you do nor have string limitations.

To keep consistent across other form elements, React uses the value prop to set “<textarea>” values:

Select

In HTML, you set the selected option using the “selected” attribute on the option tag. In React, in order to make components easier to manipulate, the following format is adopted instead:

In the next tutorial I will cover Uncontrolled components in React.js.

Article published by Javascript Evangelist and Entrepreneur Albert Cyberhulk.

  • Topics:
  • reactjs

Top Stories

High Five! You just read 2 awesome articles, in row. You may want to subscribe to our blog newsletter for new blog posts.