0

Problem: I am unable to access child state from parent component.

My approach: I can access child state from the parent if I create the state in the parent.

Question: is there any other way if I don't want to create a state in parent component and just get the data from children and make an API call?

class Parent extends React.Component {
  handleOnClick() {
    client.POST('/post/name',childStateName);
  }

  render() {
    return (
      <Child />
      <button onClick={this.handleOnClick}> save </button>
    );
  }
}

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name: 'srk'};
  }

  render() {
    return (
      {this.state.name}
    );
  }
}
Mika Sundland
  • 18,120
  • 16
  • 38
  • 50
sravan ganji
  • 4,774
  • 3
  • 25
  • 37
  • 1
    I think you really should use a single component here. A parent should not need to access the state of its children. A component should be self-contained. – Bergi Jan 04 '18 at 19:46
  • i have other functionality in child component, i just gave a part of my component since its too big – sravan ganji Jan 04 '18 at 19:48
  • is it possible to move both `handleOnClick` and the button from the parent component into the child component? – margaretkru Jan 04 '18 at 19:51
  • i can but i need to make lot of changes , that why i wanted to get the child state @margaretkru – sravan ganji Jan 04 '18 at 19:58
  • 1
    Then I think this [SO answer](https://stackoverflow.com/a/40235756/6053299) could help you. – margaretkru Jan 04 '18 at 19:59

0 Answers0