Gaurav Kandpal
Gaurav Kandpal

Reputation: 1320

How can I get the value in the parent from a child components(From Inputs)

I am creating a React Application in which I have different filters for different pages. I want to dived my whole submit form in different child components But I am not able to link value of child component in parent my code are below.

Parent Code:

import React, { Component } from 'react';
class Dash extends Component {
    constructor(props) {
    super(props);
    this.state = {
      operator: null
    };
    this.onChange = this.onChange.bind(this);

  }
  onChange(e){
    this.setState({[e.target.name]:e.target.value});
   }
  render() {
    return (
              <div className="card-body">
                  <Operator onChange={this.operator} />
              </div>
    );
  }
}
export default Dash;

Child Code :

import React, { Component } from 'react';
class Operator extends Component {
    constructor(props) {
    super(props);
    this.state = {
      operator: null
      };
      this.onChange = this.onChange.bind(this);
  }
  onChange(e){
    this.setState({[e.target.name]:e.target.value});
   }
  render() {
    const { data } = this.state;
    return (
              <div className="btn-group">
                <select className="m-wrap" id="operator-list" name="operator" onChange={this.onChange} >
                <option value="">- Choose Operator -</option>
                <option value="Digi">Digi</option>
                <option value="digi">digi</option>
                </select>
              </div>
    );
  }
}
export default Operator;

I just want to link parent class operator value with select in child class.

Upvotes: 1

Views: 20

Answers (1)

Just code
Just code

Reputation: 13801

You need to change few things onChange={this.operator} to onChange={this.onChange} in parent component

and in child

onChange(e) {
    this.props.onChange(e)    
  }

This way you are passing the onchange function to the child one and calling the parent from child component.

Demo

Upvotes: 1

Related Questions