Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a state in <Link> component of React Router?

Tags:

react-router

Here is a screenshot from their docs about <Link> component

enter image description here

  1. What state do they mean? A Redux state?
  2. How does it look like to pass a state? Like this?

        pathname: '/foo',
        query: {
            x: this.props.x,
        },
        state: store.getState()
    
like image 258
Green Avatar asked Jan 19 '17 07:01

Green


People also ask

What is state in Link react router?

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 .

What is state in react?

What Is 'State' in ReactJS? The state is a built-in React object that is used to contain data or information about the component. A component's state can change over time; whenever it changes, the component re-renders.

How do I pass state in react router Link?

With react-router, you pass state or data from one component to another component to use the react-router Link component. Data pass more quickly in the new version of react-router (v6). For example, you can pass an object's data into one component to another component.

What does Link do in react router?

A <Link> is an element that lets the user navigate to another page by clicking or tapping on it. In react-router-dom , a <Link> renders an accessible <a> element with a real href that points to the resource it's linking to. This means that things like right-clicking a <Link> work as you'd expect.


1 Answers

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:

  • Go to a Flipkart search page on a mobile device (or simulate one using Chrome DevTools)
  • Tap on one of the items

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: { ... } }
  }
}
like image 103
Eliseu Monar dos Santos Avatar answered Oct 04 '22 17:10

Eliseu Monar dos Santos