Home > Software design >  React get value from a class
React get value from a class

Time:12-13

I have a component where i get the distance from one point to another, with Google Maps (DirectionsRenderer).

What i want, is to use this data in a h1

directionsRenderer.directions.routes[0].legs[0].distance.text;

This is my return

  return (
    <>
      <div>
        <GoogleMap
          mapContainerStyle={mapContainerStyle}
          zoom={8}
          center={center}
          onl oad={onMapLoad}
        >
          {response !== null && (
            <DirectionsRenderer
              options={{
                directions: response,
              }}
              onl oad={(directionsRenderer) => {
                distanceInKm =
                  directionsRenderer.directions.routes[0].legs[0].distance.text;
                console.log("I wan't this data ->"   distanceInKm);
              }}
            />
          )}

          <DirectionsService
            options={DirectionsServiceOption}
            callback={directionsCallback}
          />
        </GoogleMap>
      </div>
      {/* THIS IS WHERE I WANT TO USE THE DATA */}
      <h1 id="calculatedDistance">{distanceInKm} km væk</h1>
    
    </>
  );
};

EDIT:

ShowProduct.js (This is where i get the distance)

import React, {
    useContext,
    useEffect,
    useState,
    useCallback,
    useRef,
  } from "react";
  import { Link } from "react-router-dom";
  
  import {
    GoogleMap,
    useLoadScript,
    DirectionsService,
    DirectionsRenderer,
  } from "@react-google-maps/api";
  
  // context
  import DbContext from "../../../context/DbContext";
  
 
  // MAP
  const libraries = ["places", "directions"];
  const mapContainerStyle = {
    width: "100%",
    height: "50vh",
  };
 

  const ShowProduct = (props) => {
    const [post, setPost] = useState();
    let [distanceInKm, setDistanceInKm] = useState(0);
    const context = useContext(DbContext);
    useEffect(() => {
      context.getProduct(props.match.params.id).then((x) => setPost(x));
    
   
    }, [context.existsUser()]);
  

    useEffect(() => {
      context.getProduct(props.match.params.id).then((x) => setPost(x));

    }, []);

    // map
    const { isLoaded, loadError } = useLoadScript({
      googleMapsApiKey: "AIzaSyCyPIhX_arhU0X62fGNLaMFassfUOmfal8",
      libraries,
    });
    const [currentPosition, setCurrentPosition] = useState({});
  
    // destination will come from Database
    let [destination2, setDestination2] = useState(
      "57.021779738464396, 9.711555234340288"
    );
  
    const success = (position) => {
      let currentPosition = {
        lat: position.coords.latitude,
        lng: position.coords.longitude,
      };

      setCurrentPosition(currentPosition);

    };
    let [origin2, setOrigin2] = useState();
  
    useEffect(() => {
      navigator.geolocation.getCurrentPosition(success);
   
    }, []);
    const [response, setResponse] = useState(null);
  
    const directionsCallback = (response) => {
      console.log(response);
  
      if (response !== null) {
        if (response.status === "OK") {
          setResponse(response);
        } else {
          console.log("response: ", response);
        }
      }
    };
  
    const mapRef = useRef();
    const onMapLoad = useCallback((map) => {
      mapRef.current = map;
    }, []);
    if (loadError) return "Error loading maps";
    if (!isLoaded) return "loading maps";
  
 
    destination2 = post?.latitude   ", "   post?.longitude;

    const DirectionsServiceOption = {
      destination: destination2,
      origin: currentPosition.lat   ", "   currentPosition.lng,
      travelMode: "DRIVING",
    };
  
    return (
      <>
        <div>
          <GoogleMap
            mapContainerStyle={mapContainerStyle}
            zoom={8}
            center={center}
            onl oad={onMapLoad}
          >
            {response !== null && (
              <DirectionsRenderer
                options={{
                  directions: response,
                }}
                onl oad={(directionsRenderer) => {
                  distanceInKm = directionsRenderer.directions
                                 .routes[0].legs[0].distance.text;
                  setDistanceInKm(distanceInKm);          
                }}
              />
            )}
  
            <DirectionsService
              options={DirectionsServiceOption}
    
              callback={directionsCallback}
            />
          </GoogleMap>
        </div>
     
        <h1 id="calculatedDistance">{distanceInKm} km væk</h1>
      
      </>
    );
  };
  
  const styleLikeButton = {
    right: 23,
    bottom: 10,
  };
  
  export default ShowProduct;
    

ProductCard.js (This is where want to use it)

import React, {
    useContext,
    useEffect,
    useState,
    useRef,
    useCallback,
  } from "react";
  import ProductCard from "react-tinder-card";
  import database from "../../../firebase";
  import "../../../styles/ProductCards.css";
  import { Link } from "react-router-dom";
  
  // Context
  import DbContext from "../../../context/DbContext";

  
  const ProductCards = () => {
    const [products, setProducts] = useState([]);
    const context = useContext(DbContext);
  
    useEffect(() => {
      if (context.existsUser() == null) {

        window.location.href = "/login";
      }

      context.getProducts().then((r) => setProducts(r));
  
      console.log(products);
    }, [context]);
  
    // TJEK swipe direction
    const onSwipe = (direction) => {
 
      if (direction == "right") {
        // product to interestsList
        console.log("Interesseret!!!");
      }
      console.log("You swiped: "   direction);
    };
  
   
    const onCardLeftScreen = (myIdentifier) => {
      console.log(myIdentifier   " left the screen");
    };

    return (
      <>
        <div>
          {products.length > 0 ? (
            <div className="productCards__cardContainer">
              {products.map((product) => (
                <ProductCard
                  className="swipe"
                  key={product.title}
                  preventSwipe={["down"]}
                  onSwipe={onSwipe}
                  onCardLeftScreen={() => onCardLeftScreen(product.id)}
                >
     
                      {/* THIS IS WHERE I WOULD LIKE TO USE THE DISTANCE */}
                      <h1>{distanceInKm} km væk</h1>
                    <h4 className="price">{product?.price} kr.</h4>
                
                    <Link
                      className="product_title"
                      to={`/showproduct/${product.id}`}
                    >
                      {product.title}
                    </Link>
              
                </ProductCard>
              ))}
            </div>
          ) : (
            "Loading..."
          )}
        </div>
  
    
      </>
    );
  };
  
  
  
  
  export default ProductCards;
  

CodePudding user response:

You need to set up a state using useState hook, before your return:

const [distanceInKm, setDistanceInKm] = useState(0);

Then in your onl oad callback, you need to set the actual value of the distance:

onLoad={(directionsRenderer) => {
  distanceInKm = directionsRenderer.directions
                 .routes[0].legs[0].distance.text;
  setDistanceInKm(distanceInKm);          
}}

And finally in your h1 you can now use the value:

<h1 id="calculatedDistance">{distanceInKm} km væk</h1>
  • Related