We can set Parent State from Children Component in ReactJs using the following approach.
Prerequisite: State introduction in ReactJS
- We will actually set the state of a parent in the parent component itself, but the children will be responsible for setting.
- We will create a function in parent to set the state with the given input.
- We will pass that function in children as a prop.
- Then Children will call the function with a new Value.
- We will set the state of the parent in the function.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder, i.e., folder name, move to it using the following command:
Project Structure: It will look like the following.
Step 3: Now create Parent and Children components in the src folder with the following code.
Step 4: Create function setStateOfParent to set state of Parent in Parent component, also pass setStateOfParent function in children.
Step 5: Now access and call the setStateOfParent function in children whenever you want to set the state of the parent.
Step to Run Application: Run the application using the following command from the root directory of the project:
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: