So, I'm having a hard time passing data between two unrelated components. I have this code below, but I don't know how to receive it from the other component
<Button
className='search__button'
variant="contained"
color="primary"
size="large"
component={Link}
to={{
pathname: "/home",
state: { data: results }
}}
>
I want to pass the variable "results" which is a Map of a string and an object Book (Map<string, Book>) to a component. Basically, my question is, how do I retrieve data in my Home component?
Thank you
When sending state with route transitions you can access it on the location
object of the receiving route in a few different ways:
In the case of functional components you can use the useLocation hook.
const { state } = useLocation();
// access state.data
If the component is rendered by a Route
on the render
, component
, or children
prop then route props will be passed to the component. location
will be a prop. Or you can decorate the component with the withRouter have have the route props of the closest matching Route
passed as props.
const { location: { state } } = this.props;
// access state.data
or
const { location: { state } } = props;
// access state.data