index
index

Reputation: 3727

react-router how do I use redirectLocation or the 301 or 302 status

We are about to deploy our site in reactjs and we have (re)moved one url but merged it in our main page so from /[product]/menu we merged it to /[product]. Now they said I should respond with 301 for /[product]/menu and redirect it to /[product], how do I accomplish that and some other pages as well?

How do I setup 301 redirects using react-router? Where do I setup what pages needs to be redirected to what other pages? I have my setup like this right now:

app.get('*', (req, res) => {
  // routes is our object of React routes defined above
  match({ routes, location: req.url }, (err, redirectLocation, props) => {
    console.log(redirectLocation);
    if (err) { // something went badly wrong, so 500 with a message
      res.status(500).send(err.message);

    // HERE: HOW DO I USE THIS?
    } else if (redirectLocation) { // we matched a ReactRouter redirect, so redirect from the server
      console.log('301/302 yeah!');
      res.redirect(301, redirectLocation.pathname + redirectLocation.search);

...

I use reactjs and express as well.

Edit Added route config.

const routes = {
  path: '',
  component: AppComponent,
  childRoutes: [{
    path: '/products',
    component: ProductsComponent,
    name: 'products'
  }, {
    path: '/:slug',
    component: ProductComponent,
    name: 'product'
  }]
}

Just in case. Added answer here:

const routes = {
  path: '',
  component: AppComponent,
  childRoutes: [{
    path: '/products',
    component: ProductsComponent,
    name: 'products'
  }, {
    path: '/:slug',
    component: ProductComponent,
    name: 'product'
  }, { 
    path: '/:product/menu', onEnter(nextState, replace) { replace(`/${nextState.params.product}`) }
  }, {
    path: '/oldlink/:testId', onEnter(nextState, replace) { replace({pathname: `http://newsite.com/oldlink/some/${nextState.params.testId}`}) }
  }]
}

Upvotes: 13

Views: 22263

Answers (2)

himanshu sharma
himanshu sharma

Reputation: 101

In the routes declaration use <Navigate.

Redirect is replaced by Navigate in the latest version of react router dom.

Example

<Route path="/services/mobile-app-development" 
   element={<Navigate to="/our-services/mobile-app-development" 
   replace /> }/>

Upvotes: 0

Damien Leroux
Damien Leroux

Reputation: 11693

In the routes declaration, use <Redirect>. Example Here

Upvotes: 3

Related Questions