user11367277
user11367277

Reputation:

React router does not understand path variable?

I have a react applicatie running in a Amazon S3 bucket, it is available here: This is the homepage of the app, the user can search ships in the search bar.

The app produces a link in the dropdown menu that looks like this:

However when the user clicks on the link you don't see the details page but the user is redirected to this page without CSS.

Locally is everything working fine.

My route component looks like this:

export class Routes extends React.Component {
render() {
    return (
        <div>
            <Route exact path={HOME_PAGE} component={Home}/>          
            <Route path={HOME_PAGE + "/details/:id"} component={Details}/>
            <Route path={HOME_PAGE + "/form/:mode"} component={Edit}/>
            <Route path={HOME_PAGE + "/form/:mode/:id"} component={Edit}/>
            <Route path={HOME_PAGE + "/csvForm"} component={CsvForm}/>
        </div>
    );
  }
}

I have build a prefix for the HOME_PAGE path that looks like this:

export const HOME_PAGE = (ENVIRONMENT == "DEVELOPMENT") ? "" : "/url"

This sets the homepage path for either development or production environment.

I was thinking of an other way to pass the ship id to the details page, maybe with a GET parameter. So the route will look something like this HOME_PAGE + /details?id=5c335682379b4d7a6ea454a8.

But I don't know if react-router supports that kind of parameter, maybe someone has a beter solution to solve this problem. Just by playing around on the website, I hope I have given enough information to understand the structure of the site.

Upvotes: 0

Views: 1876

Answers (1)

whynut
whynut

Reputation: 64

If you're using react router v4, for every Route that you defined, react-router will pass three props:

  • Match
  • Location
  • History

If you would like to access the params (which is under /:someParams), you can access the Match props by using match.params.someParams

And if you prefer the query string, you can use the Location props by using location.search which is a string so that in your case it'll return ?id=5c335682379b4d7a6ea454a8. You'll have to process the string by using qs to get your id value.

You can see the detail over here: https://reacttraining.com/react-router/core/api/Route/route-props

So in your case this would be the solution:

On your parent

<Route path={HOME_PAGE + "/details"} component={Details}/>

Your your Details Component

import qs from 'query-string'

const Details = ({location}) => {
  const {search} = location
  const queries = qs.parse(search) // you should have the query string object
  return (
    <div>{queries.id}</div>
  )
}

Upvotes: 0

Related Questions