javascriptreactjsclass

React How to Get Value of Function Component in Class based Main Component?


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


Solution

  • 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.

     // class component
     constructor(props) {
        super(props);
        this.state = {
          empSalary: "20k",
        };
      }
    
      handleSalaryChange = (newSalary) => {
        this.setState({ empSalary: newSalary });
      };
    
    
     // function component
     const [empSalary, setEmpSalary] = useState("20k");
    
      handleSalaryChange = (newSalary) => {
        setEmpSalary(newSalary);
      };
    

    Then you pass both the value and the update function to your child component

      <SalaryInfo
          empSalary={this.state.empSalary}
          onSalaryChange={this.handleSalaryChange}
        />
    

    And then use the props of your child component

    const SalaryInfo = ({ empSalary, onSalaryChange }) => {
      const handleChange = (e) => {
        onSalaryChange(e.target.value); // call parent function here
      };
    
      return (
        <FormGroup>
          <Col sm={2} style={{ textAlign: "right" }}>
            <input
              value={empSalary}  // Pass the value from parent
              onChange={handleChange}
            />
          </Col>
        </FormGroup>
      );
    };