Search code examples
reactjsimportreact-hookscomponents

how to import a function from one component react to another component to render it?


I am making my first test in react , using hooks. I have created a 'geo' component to display the coordinates on screen

import React, { useEffect, useState } from 'react';


function useCoordinates() {
    const [coordinates, setCoordinates] = useState({
        latitude: null,
        longitude: null
    });
    let geoId;

    useEffect(() => {
        geoId = window.navigator.geolocation.watchPosition(position => {
            setCoordinates({
                latitude: position.coords.latitude,
                longitude: position.coords.longitude
            });
        });
        return () => {
            navigator.geolocation.clearWatch(geoId);
        };
    });

    return coordinates;
}

export default function coordinates() {
    const coordinates = useCoordinates();

    return coordinates.latitude == null ? (
        <div>Loading ...</div>
    ) : (
        <div>
            <h2>Latitude: {coordinates.latitude}</h2>
            <h2>Longitude: {coordinates.longitude}</h2>
        </div>
    )
}


and now I'm trying to import it into my 'app' component to render it. I have imported the component and the function and I call it in the 'render' of the 'app' component, which is where I want to show it.

import React, { useState } from "react";
import "./App.css";
import { sum } from "./lib/math";
import geo, { coordinates } from './components/geo';

function App() {
  const [param1, setParam1] = useState(0);
  const [param2, setParam2] = useState(0);
  const [result, setResult] = useState(0);

  const handleSum = () => {
    setResult(sum(param1, param2));
    setParam1(0);
    setParam2(0);
  };

  const [count, setCount] = useState(0);

  return (
    <div className="App">
      <div>
        <input
          id="param1"
          type="number"
          value={param1}
          onChange={(e) => setParam1(e.target.value)}
        />

        <input
          id="param2"
          type="number"
          value={param2}
          onChange={(e) => setParam2(e.target.value)}
        />

        <button id="sum" onClick={handleSum}>
          Sumar
        </button>

        <p id="result">{result}</p>
      </div>
      <div>
        Count is: {count}
        <button onClick={() => setCount(count + 1)}>Increase</button>
      </div>
      <coordinates />
    </div>
  );
}

export default App;

console returns the following error 'React Hook "useCoordinates" is called in function "coordinates" that is neither a React function component nor a custom React Hook function.'

What am I doing wrong? How should I import it?


Solution

  • The import statement is incorrect, also you're not exporting the customHook.

    export function useCoordinates() { // maybe export this if you want to use this else where
        const [coordinates, setCoordinates] = useState({
            latitude: null,
            longitude: null
        });
        let geoId;
    
        useEffect(() => {
            geoId = window.navigator.geolocation.watchPosition(position => {
                setCoordinates({
                    latitude: position.coords.latitude,
                    longitude: position.coords.longitude
                });
            });
            return () => {
                navigator.geolocation.clearWatch(geoId);
            };
        });
    
        return coordinates;
    }
    
    export default function Coordinates() { // Pascal case is best for components
        const coordinates = useCoordinates();
    
        return coordinates.latitude == null ? (
            <div>Loading ...</div>
        ) : (
            <div>
                <h2>Latitude: {coordinates.latitude}</h2>
                <h2>Longitude: {coordinates.longitude}</h2>
            </div>
        )
    }
    

    and the import should be like this assuming you only want to import the component:

    import Coordinates from './components/geo';
    

    use it as

    <Coordinates/>