cjhines
cjhines

Reputation: 1248

Forcing onLayout on React Native view

I have a React Native View containing a Text field, and I'm using the onLayout prop to do some positional calculations which rely on the data it provides.

<View onLayout={this.calculateDimensions}>
  <Text>{this.props.content}</Text>
</View>

This works well, but there is a scenario where the content prop updates to a different string with the same character size. This results in the layout not changing and onLayout not triggering.

These positional calculations must occur each time the content prop updates.

Note: I am aware there are numerous ways to make the component update. Updating is not the same as laying out and sadly does not trigger onLayout.

Upvotes: 23

Views: 7074

Answers (2)

Jakub Kubista
Jakub Kubista

Reputation: 111

Method this.calculateDimensions needs to have some kind of indication, that it should be called again and fire re-render. I would recommend to use for its state or memo.

Let me show you an example with React Hooks. I'm setting for component onLayout, which using callback onComponentLayout. onComponentLayout has state componentHeight, which fire re-render whenever it's changed. So I'm able to change it dynamically if componentHeight is missing.

...
const onComponentLayout = useCallback(({nativeEvent: {layout}}) => {
   !componentHeight && setComponentHeight(layout.height);
}, [componentHeight, setComponentHeight]);
...

return (
...
    <Component
      onLayout={onComponentLayout}
    />
...
)

Upvotes: -1

Tom Slutsky
Tom Slutsky

Reputation: 724

You can have a unique key based on the content. whenever a key attribute of a component changes it is forcing a re-render.

Upvotes: 19

Related Questions