Artem
Artem

Reputation: 7

Trouble passing data to a child component with hooks

The structure of the project is where my App.js gets the user location when it loads. I want to take this information and pass it down to a child component. The reason I set it up like this is that I will have 3 components that all need to use the location data.

I am really close to getting this to work, but I cannot seem to get the data over to the Weather component. The App compiles successfully but it will not render the data I want it to. I feel like I am so, so close but need that push to get over the cliff.

import { Route } from 'react-router-dom'

import './App.css'; 
import Navbar from './components/Navbar'
import Weather from './components/Weather'

// Defining our <App /> component the function name matches the file name
function App() {

    const [location, setLocation] = useState({lat: 0, long: 0})

    useEffect(()=>{
      const success = (position) =>{ 
        let lat = position.coords.latitude
        let long = position.coords.longitude
   
        
        console.log(lat, long)
        setLocation({lat: lat, long: long})
        // I have also tried ({lat, long})
        
      }
      navigator.geolocation.getCurrentPosition(success)
      
    },[])



  const routes = ['nasa','openweather','zomato']

  return ( 
    <div className="App"> 

    {/* Establish Navigation for the website */}
      <Navbar routes={routes} />
      <Route exact path="/nasa"></Route>


     <Route exact path="/openweather">
        <Weather position={location} />
      </Route>


Here is the Weather component

const Weather = ({ position }) => {
    return(
        <div>
        <p> long: {position.long}</p>
        <p> lat: {position.lat}</p>
      
        </div>
    )
}

export default Weather

Upvotes: 0

Views: 53

Answers (1)

Louay Al-osh
Louay Al-osh

Reputation: 3405

Great! You've the basic idea but you are missing a little attention to your app state and everything will be okay.

1- note that you didn't pass any value to set the location state

    // first it has started with undefined
    const [location, setLocation] = useState(); // you should have passed an initila state here...

should be

    // put any default long & lat you find suitable
    const [location, setLocation] = useState({ lat: 33.232, long: 35.125 });

and when you set the new state you didn't pass anything to the set function

      setLocation()

where it should be

      setLocation({ long: <xxx>, lat: <xxx> });

2- and as I can see from your code that line should be inside the success callback where you get the actual long and lat.

3- and finally when you've passed down the state to the child component you didn't specify any property from your state(maybe because you didn't have a structure for your state yet)

        <p> {position}</p>

should be

   <p> long: {position.long}</p>
   <p> lat:  {position.lat}</p>

Upvotes: 1

Related Questions