Home > Mobile >  How to pass single data from child to parent component?
How to pass single data from child to parent component?

Time:05-31

I'm new at React native and I'm trying to pass a data(which is user current location) from child component to a parent component.

Parent

const MapScreen = ({ navigation }) => {
  const [changeMapView, setChangeMapView] = useState('standard');
  const [buttonColor, setButtonColor] = useState('#ffffff');
  const [iconColor, setIconColor] = useState('purple');
  
  let currentPosition; // varibale that I have declared 

  console.log('current position in mapscreen.js', currentPosition)

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <MapLook>
        <Map mapType={changeMapView} currentPosition={currentPosition} />
      </MapLook>

      <ButtonView>
        <SatelitViewPanel
          changeMapView={changeMapView}
          setChangeMapView={setChangeMapView}
        />

        <LocationViewPanel 
        currentPosition={currentPosition}
        />
      </ButtonView>
    </SafeAreaView>
  );
};
export default MapScreen;

Child

const Map = (props, currentPosition) => {

  const [mapRegion, setMapRegion] = useState({
    longitude: 12.5683,
    latitude: 55.6761
  });

  const getRegionForType = (type) => {
    const regionData = {
      longitude: mapRegion.longitude,
      latitude: mapRegion.latitude
    };
    return regionData;
  }
  
  const getMapRegion = () => getRegionForType('map');
  
  currentPosition = getMapRegion() // geting the current position 
  console.log(currentPosition) // in the console it shows the current position

  const getMarkerCoords = () => getRegionForType('marker');
  
  const setRegionForLocation = (location)=> {
    let coords = location.coords;
    let longitude = coords.longitude;
    let latitude = coords.latitude;

    if(mapRegion.longitude === longitude && mapRegion.latitude === latitude)
    return;

    setMapRegion({longitude, latitude, longitudeDelta, latitudeDelta});
  }

  return (
    <View style={{ flex: 1 }}>
      <MapView
        provider={PROVIDER_GOOGLE}
        style={styles.map}
        mapType={props.mapType}
      >
        {mapRegion != null && (
          <Marker coordinate={getMarkerCoords()}>
            <Image source={require('../../assets/marker.png')} style={{ height: 90, width: 90 }} />
          </Marker>
        )}
      </MapView>
    </View>
  );
};
export default Map;

When I console.log(currentPostion) in the parent component, it outputsundefined. I tried to do it with hook state, but it showed that setState is not a function

How can I pass the data from child to parent?

CodePudding user response:

You decalre your useState, ex:

const [currentPosition, setCurrentPosition] = useState();

And pass its hooks to child components:

 <LocationViewPanel 
    currentPosition={currentPosition} setCurrentPosition={setCurrentPosition}
    />

And finally, set position by using passed hook:

setCurrentPosition(getMapRegion());

So, it will work,

CodePudding user response:

hope this helps your problem.

const Map = ({currentPosition, ...props}) => {  /// need to change props in this type.

  const [mapRegion, setMapRegion] = useState({
    longitude: 12.5683,
    latitude: 55.6761
  });

  const getRegionForType = (type) => {
    const regionData = {
      longitude: mapRegion.longitude,
      latitude: mapRegion.latitude
    };
    return regionData;
  }
  
  const getMapRegion = () => getRegionForType('map');
  
  currentPosition = getMapRegion() // geting the current position 
  console.log(currentPosition) // in the console it shows the current position

  const getMarkerCoords = () => getRegionForType('marker');
  
  const setRegionForLocation = (location)=> {
    let coords = location.coords;
    let longitude = coords.longitude;
    let latitude = coords.latitude;

    if(mapRegion.longitude === longitude && mapRegion.latitude === latitude)
    return;

    setMapRegion({longitude, latitude, longitudeDelta, latitudeDelta});
  }

  return (
    <View style={{ flex: 1 }}>
      <MapView
        provider={PROVIDER_GOOGLE}
        style={styles.map}
        mapType={props.mapType}
      >
        {mapRegion != null && (
          <Marker coordinate={getMarkerCoords()}>
            <Image source={require('../../assets/marker.png')} style={{ height: 90, width: 90 }} />
          </Marker>
        )}
      </MapView>
    </View>
  );
};
export default Map;

CodePudding user response:

The data flow in React is in one way, and up to down. So you can either send a function from father to child that will set piece of state in the father

// father


const [currentPosition, setCurrentPosition] = useState();

<Map mapType={changeMapView} setCurrentPosition={setCurrentPosition} />

// child

const Map = ({setCurrentPosition, ...props}) => {  
...
setCurrentPosition(getMapRegion())

Or using state management tool as redux/mobx/context ...

Another tip, try not to declare vars and functions (const, let) in a function component unless they tied to an hook (state, ref, callback, memo...)

  • Related