google-mapsgoogle-directions-apireact-google-maps

I want pass props(origin, destination) into Map.js for DirectionsRenderer


I am using the DirectionsRenderer react-google-maps library to render the destination between two points. I would like to pass custom props for the origin and destination inside the Map.js file, here is my code;

import React from 'react'
import { withScriptjs } from "react-google-maps";
import Map from './Map'

const Directions = ({ origin, destination }) => {

    const MapLoader = withScriptjs(props => <Map {...props} />);

  return (

<div className="App">
  <MapLoader
      googleMapURL="https://maps.googleapis.com/maps/api/js?key="
      loadingElement={<div style={{ height: `100%` }} />}
  />
</div>
  );
}

export default Directions


Map.js

    import React, { useEffect, useState } from "react";
import {
    withGoogleMap,
    GoogleMap,
    DirectionsRenderer
} from "react-google-maps";

function Map({props})  {
    const [directions, setDirections] = useState(null)

   useEffect(() => {
    const google = window.google
    const directionsService = new google.maps.DirectionsService();

    const origin = { lat: 23.6238, lng: 90.5000};
    const destination = { lat: 23.8103, lng:  90.4125 }

    directionsService.route(
        {
            origin: origin,
            destination: destination,
            travelMode: google.maps.TravelMode.DRIVING,
            
        },
        (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                console.log(result)
                setDirections(result)
            } else {
                console.error(`error fetching directions ${result}`);
            }
        }
    );
   }, [])

    const GoogleMapExample = withGoogleMap(props => (
        <GoogleMap
            defaultCenter={{ lat: 23.8103, lng:  90.4125 }}
            defaultZoom={17}
        >
            <DirectionsRenderer
                directions={directions}
            />
        </GoogleMap>
    ));

    return (
        <div>
            <GoogleMapExample
                containerElement={<div style={{ height: `400px`, width: "500px" }} />}
                mapElement={<div style={{ height: `100%` }} />}
            />
        </div>
       );
    }

export default Map;

Here I want to get the destination & origin from the root route(Directions.js). Some tell me how could I pass this as props into Map.js.


Solution

  • You can't exactly use props in functional component as they are really only used in class based components. But there is a way to mimic their functionality. Since you are dealing with, functional components, you would want to make use of React hooks (useState) like you are doing already. So much like in class based components, there won't be much difference in terms of passing data. Below is a code snippet and here is a sample: https://stackblitz.com/edit/directions-eo8c6v

    index.js

    
        import React, { Component } from "react";
        import { render } from "react-dom";
        import { withScriptjs } from "react-google-maps";
        import Map from "./Map";
        import "./style.css";
        
        const { useState } = React;
        const App = () => {
          const MapLoader = withScriptjs(Map);
          const [origin, setOrigin] = useState({ lat: 23.6238, lng: 90.5 });
          const [destination, setDestination] = useState({
            lat: 23.8103,
            lng: 90.4125
          });
        
          return (
            <MapLoader
              googleMapURL="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"
              loadingElement={<div style={{ height: `100%` }} />}
              origin={origin}
              destination={destination}
            />
          );
        };
        
        render(<App />, document.getElementById("root"));
    
    

    Map.js

    
        import React, { Component } from "react";
        import {
          withGoogleMap,
          withScriptjs,
          GoogleMap,
          DirectionsRenderer
        } from "react-google-maps";
        
        const { useEffect, useState } = React;
        
        function Map({ origin, destination }) {
          const [directions, setDirections] = useState(null);
        
          useEffect(() => {
            const google = window.google;
            const directionsService = new google.maps.DirectionsService();
        
            //const origin = { lat: 23.6238, lng: 90.5 };
            //const destination = { lat: 23.8103, lng: 90.4125 };
        
            directionsService.route(
              {
                origin: origin,
                destination: destination,
                travelMode: google.maps.TravelMode.DRIVING
              },
              (result, status) => {
                if (status === google.maps.DirectionsStatus.OK) {
                  console.log(result);
                  setDirections(result);
                } else {
                  console.error(`error fetching directions ${result}`);
                }
              }
            );
          }, []);
        
          const GoogleMapExample = withGoogleMap(props => (
            <GoogleMap defaultCenter={{ lat: 23.8103, lng: 90.4125 }} defaultZoom={17}>
              <DirectionsRenderer directions={directions} />
            </GoogleMap>
          ));
        
          return (
            <div>
              <GoogleMapExample
                containerElement={<div style={{ height: `400px`, width: "500px" }} />}
                mapElement={<div style={{ height: `100%` }} />}
              />
            </div>
          );
        }
        
        export default Map;