React Native
onRegionChange
Learn map panning with onRegionChange.
onRegionChange
When the user pans or zooms the map the region changes. The onRegionChange prop of MapView takes a function called on each region change. This function receives the new region as a parameter; the region is an object and carries latitude, longitude, latitudeDelta, longitudeDelta fields.
Example: <MapView onRegionChange={(region) => console.log(region)} />. This logs the new region on every pan. You can write the region to state and use it for other purposes; for example, you can load businesses in the user's current region. onRegionChangeComplete is called once when the pan stops; this reduces unnecessary calls.
Region state
You keep the region in state: const [region, setRegion] = React.useState(null). Inside the onRegionChange function you update it with setRegion(newRegion). When state updates the component re-renders; you can use the region during this.
For example, to show a text at the top of the screen: <Text>Latitude: { region.latitude.toFixed(4) }</Text>. This updates the latitude value on every pan. Since onRegionChange is called very often, leaving heavy work to onRegionChangeComplete may be better. This is called once when the user stops panning; it preserves performance.
Exercise Log the region change
Complete the empty App component. Return <MapView style={{{ flex: 1 }}} initialRegion={{{ latitude: 41.0082, longitude: 28.9784, latitudeDelta: 0.05, longitudeDelta: 0.05 }}} onRegionChange={(region) => console.log(region)} />.
Show example solution
return (
<MapView
style={{ flex: 1 }}
initialRegion={{
latitude: 41.0082,
longitude: 28.9784,
latitudeDelta: 0.05,
longitudeDelta: 0.05,
}}
onRegionChange={(region) => console.log(region)}
/>
);
Test yourself
-
Write the function parameter
onRegionChange={(____) => console.log(region)}
Show answer
onRegionChange={(region) => console.log(region)}
-
Match each prop to its purpose
- onRegionChange
- Called on every change
- onRegionChangeComplete
- When pan stops
- region
- Region object
- setRegion
- Updates the region
-
When is onRegionChange called?
<MapView onRegionChange={(region) => { ... }} />
- Only when the app opens
- Only when the marker is tapped
- Only when permission is granted
- On every region change
Show answer
On every region change — onRegionChange fires on every region change.
Next lesson: Custom marker