Home > Back-end >  Pass width and height of a <View> to a child component
Pass width and height of a <View> to a child component

Time:11-29

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

CodePudding user response:

Alternative solution with the useState hook:

export default function App()  {

  const [width, setWidth] = useState(0);
  const [height, setHeight] = useState(0);

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

CodePudding user response:

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.

  • Related