DEV Community

Cover image for What is a state controlled form in React js?
Suman Roy
Suman Roy

Posted on • Edited on

What is a state controlled form in React js?

In this blog we are going to discuss controlled form in React js.

Pre-requisites : You only need to know basics of React and it's hooks. If you don't know, I am sure you can follow along as it is beginner friendly

So, for controlled form inputs, we are going to use

  • useState hook
  • onChange event

What is useState?
It is a react hook (special functions) that allows you to have state variables in functional components. You pass the initial state to this function and it returns a variable with the current state value and a function for manipulating the state value.

What is onChange event ?
The onChange event in React detects when the value of an input element changes. It is triggered when the element loses focus.

Now, let's see the code

import {useState} from 'react';

export default function App() {
  const [name, setName] = useState("");

  const handleSubmit=(e)=>{
       e.preventDefault();
       // probably console log it or send to server via api
  } 

  return (
    <div className="App">
      <h1>
        React form
      </h1>
      <form onSubmit={handleSubmit}>
        <input 
        type="text"
        value={name}
        onChange={(e)=> setName(e.target.value)}
        placeholder="Enter name..."/>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Here, we have converted a normal form to a controlled form. It is because we are controlling the form data via states. The initial state is being taken value attribute, now whenever we change the input field, the onChange event will be triggered and setName function will be invoked to change the value of name to the input inside the field e.target.value. This way, we are letting React handle our form data in the component itself.


That is the end. If you have any query, drop it in the comment section below. If you think this blog has any error or wrong info, please let me know.

I hope I could help you understand the topic 😀. If yes, please share it with your friends and others so that this could benefit them too! Till then , keep REACT-ing ❤🚀

Follow me on:
Github
LinkedIn
Twitter

Top comments (0)