DEV Community

Walktheworld
Walktheworld

Posted on

Controlled Components

A controlled component is a component that renders form elements and controls them by keeping the form data in the component's state.

A controlled form is a form that gets its input values from the state.

Let's take a look at what that looks like:

First, we need to create a component that has an initial state. In this case, I use an empty string as my initial colorInput state:
component state

Then, we render the form to the page to make sure that everything is connected properly (don't forget to import it to your main container and add to to the render lifecycle) :
render

Next, we need to handle the change of state, so we will implement a handleColorInput function for our in-line onChange event, and tell the style to change the color of the text from the state:

So here is the whole code:
whole code

and this is what that code returns:
input form input form input form input form

Top comments (0)