0

I want to click a link with a search string. But the react router does not direct to that page. After refresh the page gets loaded. Is something wrong?

URL

 http://localhost:3000/landing?cars

Link button

                <Button
                 component={Link}
                 to={{pathname: "/landing?cars"}}
                 >
                 Cars
                </Button>

router

<Switch>
    <Route path="/landing" component={Landing} />
    ...
</Switch>
8
  • why not just to="/landing?search=cars" Commented Nov 9, 2020 at 15:51
  • @lala it also doesn't work Commented Nov 9, 2020 at 15:53
  • Oh my bad. In <Route path="/landing/:search" component={Landing} /> and to="/landing/cars". Then in landing page you can use const {search} = useParams(). But first make sure to import it from const { useParams } from 'react-router-dom' Commented Nov 9, 2020 at 15:57
  • or you can refer here for both, using query or param Commented Nov 9, 2020 at 16:04
  • 1
    you can refer to this sandbox Commented Nov 9, 2020 at 17:12

1 Answer 1

1

Need an optional parameter:

<Switch>
    <Route path="/landing/:search" component={Landing} />
    ...
</Switch>

<Button
    component={Link}
    to="/landing/cars"
    />
    Cars
    </Button>

Then in the Landing page you can access the parameter using the match object. For example:

const { searchValue } = this.props.match.params.id;
Sign up to request clarification or add additional context in comments.

2 Comments

With your suggestion the routing works, but a hard refresh will reult in a blanc page, because then I think :search is undefined. With your solution you cannot share the link. Do you know how to fix it?
@vuvu What do you mean by share the link, can you create a code sandbox of your issue/ problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.