Open In App

What are Controlled components in ReactJS ?

Last Updated : 24 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

React’s Controlled Components manage form data via component state, receiving values through props and updating through callbacks like onChange. The parent component maintains the state, passing updated values as props to the controlled component. Form elements, whether typed (e.g., textarea, input) or selected (e.g., radio buttons, checkboxes), trigger state updates through functions on change.

Prerequisites:

Steps to Create the React Application And Installing Module:

Step 1: Create the react app using the following command:

npm create-react-app project

Step 2: After creating your project folder(i.e. project), move to it by using the following command:

cd project

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}

Example: A React form utilizes useState hooks for ‘showName’ (boolean) and ‘name’ (string). The ‘handleSubmit’ onClick function prevents default submission behavior, sets ‘showName’ to true, and displays the entered name upon form submission.

Javascript




import { useState } from "react";
 
function App() {
    const [name, setName] = useState("");
    const [showName, setShowName] = useState(false);
 
    function handleSubmit(e) {
        e.preventDefault();
        setShowName(true);
    }
 
    return (
        <div className="App">
            <form>
                <label>Name:</label>
                <input
                    name="name"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                />
                <button onClick={handleSubmit} type="submit">
                    Submit
                </button>
            </form>
            {/* Checks the condition if showName is
      true, which will be true only if
      we click on the submit button */}
            {showName === true && <p>You have submitted. Name: {name}</p>}
        </div>
    );
}
 
export default App;


Step to Run the application: Run the application using the following command from the root directory of the project:

npm start

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads