onRegionChange
- React Native course
- Advanced
- Lesson 28/83
- 5 min
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.
Practice 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)} />.
Starter code
import { MapView } from 'react-native-maps';
export default function App() {
// log the region change
return null;
}Sample solution
return (
<MapView
style={{ flex: 1 }}
initialRegion={{
latitude: 41.0082,
longitude: 28.9784,
latitudeDelta: 0.05,
longitudeDelta: 0.05,
}}
onRegionChange={(region) => console.log(region)}
/>
);Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the function parameter
onRegionChange={(____) => console.log(region)}
onRegionChange={(region) => console.log(region)}
Explanation: The region parameter carries the new region.
2 Match each prop to its purpose
| Term | Meaning |
|---|---|
onRegionChange |
Called on every change |
onRegionChangeComplete |
When pan stops |
region |
Region object |
setRegion |
Updates the region |
3 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 Correct answer
Explanation: onRegionChange fires on every region change.