Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactNative: ref and onLayout on custom component

I have a custom Component as below. Interestingly, the ref isn't being setup and onLayout isn't being fired. These problems get resolved if I wrap MyView inside another View in the Parent class.

Neither ref nor onLayout work

const MyView = props => 
      <View style={{flex: 1}}>
        {this.props.children}
      </View>

Ref works here

class MyView extends Component {
  render() {
    return (
      <View style={{flex: 1}}>
        {this.props.children}
      </View>
    )
  }
}

Sample usage

class Parent extends Component {
  render() {
    return (
      <MyView ref={c => this.myView = c} onLayout={e => console.log(e)} />
    )
  }
}
like image 312
Anshul Koka Avatar asked Oct 14 '25 04:10

Anshul Koka


1 Answers

ref would work only on components which is why it isn't working in the first scenario.

onLayout is a method of View and doesn't get inherited by every Component. Passing in a prop and setting it on a containing View would solve the problem.

like image 149
Anshul Koka Avatar answered Oct 16 '25 22:10

Anshul Koka