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!
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}`);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.