0

I am working on a project in React, and one of the last things I want to do is use buttons on the homepage to navigate to a Map component and change the starting location. So essentially on the homepage a user would click 'Washington, DC' and it would route to my /map and also pass the map starting coordinates for DC. I my question is what would be the most proper way to do this? My current code, that doesn't work as I'm still debating the architecture of this, looks like:

   <button
     className="tourButtons"
     onClick={() => {
       <Route exact path="/home" render={ (washington) =>
          <Map {...washington} />
       }/>
     }}
    >
    Washington, DC
   </button>

My Map is a functional component that has a default center if you load via a different button. Relevant parts of that code should only be: const center = { lat: 39.7459467, lng: -75.5465889, }; and <GoogleMap center={center}>

My router in /App currently looks like (added homepage last, eventually changing that route around so home is at / and map is at /map)

 <Switch>
      <Route exact path="/home" component={Home}></Route>
      <Route exact path="/" component={Map}></Route>
      <Route exact path="/suggest" component={Form}></Route>
 </Switch>

Ramblings on what resources and ideas I've come up with so far include:

I feel like this question is trivial, but am asking so I can form good habits going forward. Thanks!

1 Answer 1

1

You can create a new <Route/> on the /App. You can pass the props down to Map as needed.

<Route
    path='/map'
    render={(props) =>
        <Map
            {...props}
            coords={this.state.coords}
        />
    }
/>

Since you are on the Home component, you probably need to pass a function from App down to Home via prop so you can update the, for example, coords state on the App which you will be passing as prop down to Map. Example code on App:

updateCoords = (val) => {
    this.setState({
        coords: val
    })
}

<Route
    path='/home'
    render={(props) =>
        <Home
            {...props}
            updateCoords={this.updateCoords}
        />
    }
/>

Then on Home simply call this.props.updateCoords(someValue) to update the state of the coords state on your App.

If you need to redirect right away I suggest using the <Link> (https://reactrouter.com/web/api/Link) or use history api on App

this.props.history.push(`/${someRoute}`);
Sign up to request clarification or add additional context in comments.

1 Comment

<Link> is exactly what I was looking for, just have to change the styling around to make it span like a button. I then added (props) to my functional component and called it in my google maps wrapper.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.