PraveenKumar Invoscape PraveenKumar Invoscape - 3 months ago 8
React JSX Question

Reactjs:Is it possible to use Parent component property from another Parent's child component

I have a file named separatefile.jsx, in this file parent component name is Content and child component name is Child.

separatefile.jsx



import React from 'react';
import Parent from './learning.jsx';

class Content extends React.Component {
constructor() {
super();
this.state = {
finding : 'i am finding'
}
}
render() {
return (
<div>
<Child childprop={this.state.finding}/>
<Parent/>
</div>
);
}
}

class Child extends React.Component {
render() {
return (
<div>
<h2>{this.props.childprop}</h2>
<h1>child class property</h1>
</div>
);
}
}
export default Content;





This is another file named as learning.jsx , this file has Parent component named as Parent and Child component named as a Children.

My questions is that i need to access Parent component property(parent component for learning.jsx) from Child component(child component for separatefile.jsx file)...

learning.jsx



import React from 'react';


class Parent extends React.Component {
constructor() {
super();
this.state = {
searching : 'i will find the solution'
}
}
render() {
return (
<div>
<Children childrenprop={this.state.searching}/>
</div>
);
}
}

class Children extends React.Component {
render() {
return (
<div>
<h2>{this.props.childrenprop}</h2>
</div>
);
}
}
export default Parent;




Answer

If I understood you correctly, you want to use Parent's state in your Children component?

You can pass it down the component tree as props, e.g.:

class Content extends React.Component {
  constructor() {
    super();
    this.state = {
      finding : 'i am finding'
    }
  }
  render() {
    return (
      <div>
        <Child childprop={this.state.finding}/>
        <Parent finding={this.state.finding} />
      </div>
    );
  }
}

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      searching : 'i will find the solution'
    }
  }
  render() {
    return (
      <div>
        <Children finding={this.props.finding} childrenprop={this.state.searching}/>
      </div>
      );
  }
}

class Children extends React.Component {
  render() {
    return (
      <div>
        <h2>{this.props.childrenprop}</h2>
        <div>{this.props.finding}</div>
      </div>
    );
  }
}