1

I have a React App where I have an event listener for resize event on the window object.

class App extends React.Component {
  constructor(props){
    super(props);

    this.state = { width: 0 }
    this.setSize = this.setSize.bind(this);
  }

  render() {
    let content = this.state.width < 600 ? <MobileComponent/> : <DesktopComponent />;
    return(<div>{content}</div>)
  }

  setSize() {
    this.setState({
        width: window.innerWidth
    });
  }

  componentDidMount() {
    this.setSize();
    window.addEventListener('resize', this.setSize);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.setSize);
  }
}

This thing work but my problem is that I dont know how to access the state of the App component (the window width) inside child components.

So, can someone explain me how to access/send this.state.width in my children components (i know i can send with props, but what if in my I have 2 more components?)

Pavlo
  • 43,301
  • 14
  • 77
  • 113
Hiero
  • 2,182
  • 7
  • 28
  • 47

1 Answers1

3
      render() {
        let content = this.state.width < 600 ? <MobileComponent/> : <DesktopComponent />;
        return(<div>
            <div>{content}</div>
            <childComponent myWidth= {this.state.width}></childComponent >
            <childComponent2 myWidth= {this.state.width}></childComponent2 >
       </div>
      )
 }
Pavlo
  • 43,301
  • 14
  • 77
  • 113
Ved
  • 11,837
  • 5
  • 42
  • 60
  • thank you for the answer, and if childComponent has childComponent should I add props too? Its a good practice? – Hiero Apr 08 '16 at 12:27
  • Yes. you can. If a chilcomponent have childcomponent than also follow the same approach. – Ved Apr 08 '16 at 12:29