What are Controlled components in ReactJS ?
In React, Controlled Components are those in which form’s data is handled by the component’s state. It takes its current value through props and makes changes through callbacks like onClick,onChange, etc. A parent component manages its own state and passes the new values as props to the controlled component.
In the form elements are either the typed ones like textarea. input or the selected one like radio buttons or checkboxes, whenever there is any change, made it is updated accordingly through some functions that update the state as well.
- Knowledge about reactJs.
- Knowledge about react hooks
Creating React Application:
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:
Project Structure: It will look like this.
Example: We are creating a simple form with having input field names and a button to submit. We are using react hook useState to maintain two of our states showName and name which stores a boolean value and a string respectively.
We are creating an onClick function named as handleSubmit which prevents the default behavior of submit button and sets the showName to true. And after clicking on the button i.e submitting our form we are displaying the name that we have entered.
Steps to run the application: Run the application using the following command from the root directory of the project:
Please Login to comment...