2

I want call a method for the MapView component found in the docs. Here

I have absolutely no idea how to do it.

const Map = props => {
const mapRef = useRef();
const random = () => {
    console.log(mapRef);
    console.log(mapRef.current.getCamera());
}

return <MapView ref={mapRef} onClick={random()} style={styles.mapStyle}  provider={PROVIDER_GOOGLE} region={props.region} />;

};

This is what I tried based on what I found online but I keep getting undefined is not an object (evaluating 'mapRef.current.getCamera')

1 Answer 1

3

What's going on here is that you are calling random function when the component is rendered and at this point the mapRef is null.

The other thing is, as I know, React Native components doesn't have onClick methods, in mobile development it is called onPress.

So you need to change your onClick={random()} to onPress={random} look that I erased the parentheses and changed the name of the method.

look at this example

export default function App() {
  const mapRef = useRef(null);
  const [text, setText] = useState('');

  const handleMapPress = () => {
    const region = {
      latitude: 37.78825,
      longitude: -122.4324,
      latitudeDelta: 0.0922,
      longitudeDelta: 0.0421
    };
    mapRef.current.animateToRegion(region); // Here I'm using one of the map methods
  }
    return (
      <View style={styles.container}>
        <Text>{text}</Text>
        <MapView ref={mapRef} onPress={handleMapPress} style={styles.mapStyle} />
      </View>
    );
}

You can see it working in this expo snack

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.