Here is a screenshot from their docs about component
state
do they mean? A Redux
state?In simple term state in <Link/>
component is use to pass information from one view to other view through router in form of object.On other page it can be access using prop.location.state
.
(Note: on browser refresh state no longer contain information)
To pass state in Link:
<Link to={{pathname: "/second_page", state: {id: 123}}} />
To access id in second page view:
let id = props.location.state.id;
For more Link properties : React Router Link
The the state
property of the to
prop is the param of pushState
method of History
DOM object described here
That props used in push
/replace
methods of router as described here for transitions to a new URL, adding a new entry in the browser history like this:
router.push('/users/12')
// or with a location descriptor object
router.push({
pathname: '/users/12',
query: { modal: true },
state: { fromDashboard: true }
})
It also mentioned here:
router.push(path)
router.push({ pathname, query, state }) // new "location descriptor"
router.replace(path)
router.replace({ pathname, query, state }) // new "location descriptor"
state
is a property that's part of the object you can provide to the to
prop of the <Link>
component.
It is particularly useful if you want to send data from the current view to one the <Link>
directs you to, without using common techniques such as setting URL parameters or using libraries, such as Redux
.
There isn't much official information about the state
key, but here's what I found in the source code of that component:
Links may pass along location state and/or query string parameters in the state/query props, respectively.
So basically, it's like sending props to a component from a parent. Here, you are sending "state" from the current view to the target view. That's about it, really.
It's a piece of information that you'd like to send to the next page. Nothing to do with Redux. It's a plain object. I believe Flipkart is a very nice example of how it can be used to improve user experience:
You'll see that the transition happens instantly and pieces of information like product images, title, rating and price are readily available on the product page. One way to implement that is passing the state they had already loaded on the search page onto the next one:
<Link
to={`/product/${id}`}
state={{
product,
}}
/>
And then:
function ProductPage(props) {
// Always check because state is empty on first visit
if (props.location.state.product) {
console.log(props.location.state.product);
// { id: '...', images: [...], price: { ... } }
}
}