ptts
ptts

Reputation: 1053

How to access a parent components state in react

I want to access the state of my parent component SubmitForm and return the result by returning a span element with the query result.

The fake DB or JSON file is:

const citi = [
  {
    pc: '13000',
    city: 'berlin',
    population: '10million'
  }, {
    pc: '81000',
    city: 'munich'
  }
];

These are the change and submit event handlers:

handleChange(event) {

  this.setState({ value: event.target.value });
}

handleSubmit(event) {
  alert('We will find the city for postal code: ' + this.state.value);
  event.preventDefault();
  var result = citi.filter(obj => obj.pc === this.state.value)[0].city;
  console.log(result);
  this.setState({ value: result });
}

And the render method

render() {
  return (

    <form onSubmit={this.handleSubmit}>
      <label>
        Search by postcode:
     <input type="text" value={this.state.value} onChange={this.handleChange}
        />
      </label>
      <button type="submit" className="btn btn-default">Search</button>
      <ComponentB />
    </form>
  );
}

This is the child component

class ComponentB extends React.Component {
  constructor(props) {
    super(props);
    // this.state = {val: 'hdgfh'};

  }


  render() {
    return <span>The postcode is in : {this.props.value}</span>;
  }
}

When i render all in the parent component, everything works, but how can I render in the parent and display the result? Console logs the right result, but all questions regarding accessing parent/children state were not helpful enough to me.

Codepen link:

https://codepen.io/damPop/pen/ReXwoo?editors=0010

Upvotes: 1

Views: 62

Answers (2)

jmargolisvt
jmargolisvt

Reputation: 6088

You should pass the parent's state as a prop like so:

<ComponentB value={this.state.value}/>

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196236

You would need to pass down the value through props (they are not inherited)

so

<ComponentB value={this.state.value} />

Updated pen: https://codepen.io/anon/pen/jQNvOe?editors=0010

Upvotes: 1

Related Questions