virendra parade
virendra parade

Reputation: 151

React Get Another Component State

Hello I had just started with react not much familiar with getting the state of another component in master component. Can anyone please help here out.

Scenario I have 4 Component namely A, B, C, D

Code Bellow for Reference

Component A

class A extends Component {
 constructor() {
  super();
  this.state = {
  Acomp:''
  };
}
render() {
return (
  <B/>
 )
}
}
export default A;

Component B

 class B extends Component {
 constructor() {
  super();
  this.state = {
  Bcomp:''
  };
}
render() {
return (
  <C/>
  <D/>
 )
}
}
export default B;

Component C

 class C extends Component {
 constructor() {
  super();
  this.state = {
  Ccomp:''
  };
}
render() {
return (
  <h1>i am Component C</h1>
 )
}
}
export default C

Component D

 class D extends Component {
 constructor() {
  super();
  this.state = {
  Dcomp:''
  };
}
render() {
return (
  <h1>i am Component D</h1>
 )
}
}
export default D

Upvotes: 1

Views: 2588

Answers (2)

theabrar
theabrar

Reputation: 440

You can create your state in Component A and pass them as props to Component B, C and D.

Component A

class A extends Component {
 constructor() {
  super();
  this.state = {
    Acomp:'',
    Bcomp:'',
    Ccomp:'',
    Dcomp:'',
  };
 }

onChange = () =>{
//Write your function to change the value of state here
}


render() {
return (
  <B BComp = {this.state.Bcomp} CComp = {this.state.Ccomp} DComp = {this.state.Dcomp} onChange={this.onChange}/>
 )
}
}
export default A;

Component B

class B extends Component {
 constructor() {
  super();
  this.state = {
  Bcomp:''
  };
}
render() {
return (
  <C Ccomp={this.props.CComp} onChange={this.onChange}/>
  <D Dcomp={this.props.DComp} />
 )
}
}
export default B;

And you can also pass your onChange function if required as props to Components C & D.

Upvotes: 1

Addison
Addison

Reputation: 169

You'll need to lift your component state up through your components

See https://reactjs.org/docs/lifting-state-up.html for more info!

Upvotes: 0

Related Questions