6

I have a route set up:

<Route path="/search/:name" component={foo} />

In a component I am trying to redirect based on the entered name:

<Redirect to="/search" />

I want to pass this.state.name to the Redirect, like /search/name. How?

7
  • 3
    If the this.state.name is available in the scope, you can simply write <Redirect to={`/search/${this.state.name}`} /> Commented Jul 28, 2017 at 12:10
  • When results are printed I get: Search results for ${this.state.name} as a string... Commented Jul 28, 2017 at 12:13
  • Ideally I would do: <Redirect to="/search" + this.state.name /> but React complains about that Commented Jul 28, 2017 at 12:15
  • 1
    Sorry, I've updated the comment. SO's formatting was a bit messed up. React complained because, you're writing JS code inside the JSX syntax. It needs to be enclosed in { } Commented Jul 28, 2017 at 12:16
  • This still isn't working - it's just printing out the result as a string Commented Jul 28, 2017 at 12:18

1 Answer 1

13

Resolved:

I had to wrap in curly braces like so:

<Redirect to={"/search/" + this.state.name} />

(Thanks to Giri for guidance)

Sign up to request clarification or add additional context in comments.

1 Comment

No problem!. I see you got confused a bit while I was using backticks instead of quotes. Sorry about that!. But avoid these kind of string concatenation wherever possible by using the backticks. For more info, Have a look at this

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.