I Moved one form outside my Class Component.
Eg: main.js
<FormGroup>
<Col sm={2} style={{ textAlign: 'right' }}>
<input ref='emp_name' value='sam' />
</Col>
</FormGroup>
<FormGroup>
<Col sm={2} style={{ textAlign: 'right' }}>
<input ref='emp_salary' value='20k' />
</Col>
</FormGroup>
I moved salary portion into function component into separate js file.
SalaryInfo.js:
<SalaryInfo
<FormGroup>
<Col sm={2} style={{ textAlign: 'right' }}>
<input ref='emp_salary' value='20k' />
</Col>
</FormGroup>
</SalaryInfo>
but am not able to get value of emp_salary
in main.js
How to get value of Child component in main component?
I tried ‘refs’ also state / props nothing helps.
am using react 16.14.0
2
Answers
The easiest way to solve this is to follow React’s unidirectional data flow by managing state in the parent and passing it to the child as props.
So in your case, you want to have a local state using useState or this.state for a class to contain your value in your Main.js. Then pass the value and the update function as well to your child component as props. So when the input of your child component is updated, the update function will be fired and will update the state of the parent component and you will have access to the value.
In your main.js class component you will have a state to manage the value and a method to update it. If you want to convert it into a function component just use the useState hook instead.
Then you pass both the value and the update function to your child component
And then use the props of your child component
So the use of ref attribute is a red flag. Sure it’s allowed, but do you really need direct access to the input element?! Presumably you’ve refactored your main code to something like this:
You want to stick to the basics and that’s props. So do the following:
Then in SalaryInfo
They are sharing the employee instance so they both have access to the full object and its properties. The SalaryInfo component just looks at different property.