AdrienM
AdrienM

Reputation: 184

onLayout not being called

This is an extract of my code:

render() {
    console.log("first log");
    return (
        <View onLayout={e => console.log("second log")}>
...

The console displays "first log" but not the second one. The view seems to render correctly. I tried with other views but the result is the same. I'm using react-native 0.48.4.

Upvotes: 11

Views: 15800

Answers (2)

Stanislav Mayorov
Stanislav Mayorov

Reputation: 4452

In my case onLayout isn't called because items were rendered in FlatList so only several items were rendered on mount.

Upvotes: 3

Jiana
Jiana

Reputation: 96

I solved this by changing initial height bigger than 0, then onLayout function successfully fired when ChildView's layout has been changed.

  constructor(props) {
    super(props);
    this.state = {
      title: '',
      height: 0 // changed to 1
    };
  }
  onLayout = (event) => {
    console.log('on layout:')
    const {
      x,
      y,
      width,
      height
    } = event.nativeEvent.layout;
    console.log(x, y, width, height);
  }
  render() {
    return (
      <View style={[styles.container, {height: this.state.height}]}>
        <View onLayout={this.onLayout}>
          <ChildView/>
        </View>
      </View>
    )
  }

Due to this Breaking Change: Android: Only call onLayout when layout has actually changed https://github.com/facebook/react-native/wiki/Breaking-Changes#android-only-call-onlayout-when-layout-has-actually-changed-15429e---astreet

Upvotes: 8

Related Questions