Can't figure out how to Link state with React Router

Viewed 15

I have my "Link to" under a text field that updates my states but I get an error why I try the results.

The error I get is: TypeError: Cannot read property 'getProps' of undefined

This is my AdvancedSearch page:

<Link
    to={{
        pathname: "/Results",
        getProps: {
            searchGet: this.state.search,
            movieGet: this.state.movies,
            totalResultsGet: this.state.totalResults,
            currentPageGet: this.state.currentPage
        }
    }}>
        <Button variant='contained' > Show results </Button>
</Link>

And this is the Results page that I want the states to be transferred to:

const Results = (props) => {
        console.log("about",props.location.getProps)
        return (
            <div>
                Test
            </div>
        )
    }
1 Answers

This is what the state prop is for. Docs here

Here is what you need. Your Link component should look like this:

 <Link
  to={{
     pathname: "/movie",
     state: {
       searchGet: "Val 1",
       movieGet: "Val 2",
       totalResultsGet: " Val 3",
       currentPageGet: "Val 4"
     }
  }}
 >
  Movie
 </Link>

And the way you would access that state in the Result component is...

const { searchGet, movieGet } = props.location.state;

This will only work though if you render your Result component as part of the Router like so:

<Switch>
...
...
  <Route path="/movie" component={Result} />
</Switch>

Here is a Sandbox for you to play around with.

Related