onLayout
- React Native course
- Beginner
- Lesson 80/116
- 5 min
Learn layout events with onLayout.
The onLayout event
onLayout fires when a component is laid out on the screen. It gives position, size and layout info; these are often used for custom drawing or measured layouts.
Example: <View onLayout={'{(event) => setWidth(event.nativeEvent.layout.width)}'}>. Here layout.width gives the View's width. You can store that in state and use it for further calculations.
onLayout fires only when layout changes; not on every render. That makes it ideal for catching rotation or window resize events.
Reading the layout object
The event from onLayout has a nativeEvent.layout field with four values: x, y, width, height.
x and y are the position of the component relative to its parent. width and height are the measured sizes. These can be stored in state and used later.
Example: a chart width can be taken from an inner View's onLayout and used in drawing math. This is a common pattern for responsive charts.
Practice Store the width in state
Write an App component. Define width with useState(0). Give the <View> an onLayout handler that calls setWidth with event.nativeEvent.layout.width. Put <Text>{`{width}`}</Text> inside. Export the App function.
Starter code
import { useState } from 'react';
import { View, Text } from 'react-native';
// write the code that stores width in state hereSample solution
function App() {
const [width, setWidth] = useState(0);
return (
<View onLayout={(event) => setWidth(event.nativeEvent.layout.width)}>
<Text>{width}</Text>
</View>
);
}
export default App;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does onLayout fire?
- When layout changes
- On every render
- Only when a button is pressed Correct answer
- Only on first mount
Explanation: onLayout fires whenever layout changes.
2 Add onLayout
import { View, Text } from 'react-native';
function App() {
return (
<View ____={(event) => console.log(event.nativeEvent.layout.width)}>
<Text>Measure</Text>
</View>
);
}
import { View, Text } from 'react-native';
function App() {
return (
<View onLayout={(event) => console.log(event.nativeEvent.layout.width)}>
<Text>Measure</Text>
</View>
);
}
Explanation: onLayout listens for the layout event.
3 Match the onLayout parts
| Term | Meaning |
|---|---|
onLayout |
Listens to the layout event |
nativeEvent.layout |
Layout data |
width |
Horizontal size |
height |
Vertical size |