DEV Community

Cover image for What I learned : Controlled Components
Snap Dragon
Snap Dragon

Posted on • Updated on

What I learned : Controlled Components

A controlled component is one where the form's data is handled by state. Here are the steps to create a controlled component.

  1. Import the useState hook from the react library.

  2. Create the state inside of the component that will handle the form data.

  3. Set the value of the input to the state variable.

  4. Update the state every time in changes.

import {useState} from "react";
function App() {
    const [country, setCountry] = useState("");
    return <select value={country} onChange={e => setCountry(e.target.value)}>
        <option>Country</option>
        <option value="france">France</option>
        <option value="spain">Spain</option>
        <option value="germany">Germany</option>
    </select>
}

Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
naucode profile image
Al - Naucode

Great article, you got my follow, keep writing!

Collapse
 
snappdragon profile image
Snap Dragon

Thank you. I appreciate it.