Search code examples
react-nativeviewreact-props

Pass width and height of a <View> to a child component


I'm new to react. I have the width and height of a <View> and I'd like to pass theses datas to a <Child> component which contains these two props. I have destructurate the <View> layout in width and height but it seems that I can't pass theses variables to the <Child>(undefined name).

Here's the code:

  <View onLayout={(event) => { let { width, height } = event.nativeEvent.layout;}} >
    <Child width={width} height={height } />
  </View>

Thanks


Solution

  • If you pay attention to you code you will see that width and height are not in scope. They exist in the scope of your event handler. Hence, you are passing variables that don't exist to the child.

    Also, a proper way to do it would be using state. For example, if your view is created in a class called AppView then

    class AppView extends React.Component {
      constructor(props) {
        super(props)
        this.state = {
          width: null,
          height: null,
        }
      }
      render() {
        return (
          <View onLayout={(event) => {
            let { width, height } = event.nativeEvent.layout
            this.setState({width: width, height: height}
          }}>
            <Child width={this.state.width} height={this.state.height} />
          </View>
        )
      }
    }
    

    This way everytime the onLayout event is triggered it will set the state variables width and height. This modified values will then be passed to the child element.