How to make /92329 redirect to /products/92329 in React

Viewed 48

the users will came to the page from a QR link (that I can't change), the link is configured to be mypage.com/[EAN] i.e. mypage.com/4345674299043 ean is always a number with 13 digits on it. So when users enter the site with this kind of link, I should redirect them to mypage.com/products/[EAN] in the example case it'll be mypage.com/products/4345674299043

I tried to use routing inside app.js but it didn't work. I'm getting 404

2 Answers

Something like this at some place in your page that is run fairly early.

This looks at the path i.e. what comes after a '/' in a url and checks if it has 13 digits. if it does we redirect to your page. now including '/products.

There is room for improvement in below snippet, but it should give you the idea.

const path = window.location.pathname;
if (path.match(/(\d){13}/gi)) {
    window.location.href = `mypage.com/products/${path}`
}

The general gist is that you create a custom component to read the EAN value as a path parameter and redirect to the correct target path if it is a valid 13-digit EAN, or back to the home path "/" (or similar) if not valid.

react-router-dom@5

import {
  Switch,
  Route,
  Redirect,
  useParams,
  generatePath
} from "react-router-dom";

...

const ProductRedirect = () => {
  const { EAN } = useParams();
  const isValidEAN = EAN.match(/(\d){13}/gi);
  return (
    <Redirect to={isValidEAN ? generatePath("/products/:EAN", { EAN }) : "/"} />
  );
};

...

<Switch>
  <Route path="/products/:EAN" component={Product} />
  <Route path="/:EAN" component={ProductRedirect} />
</Switch>

Edit how-to-make-92329-redirect-to-products-92329-in-react (RRDv5)

react-router-dom@6

import {
  Routes,
  Route,
  Navigate,
  useParams,
  generatePath
} from "react-router-dom";

...

const ProductRedirect = () => {
  const { EAN } = useParams();
  const isValidEAN = EAN.match(/(\d){13}/gi);
  return (
    <Navigate
      replace
      to={isValidEAN ? generatePath("/products/:EAN", { EAN }) : "/"}
    />
  );
};

...

<Routes>
  <Route path="/products/:EAN" element={<Product />} />
  <Route path="/:EAN" element={<ProductRedirect />} />
</Routes>

Edit how-to-make-92329-redirect-to-products-92329-in-react (RRDv6)

Related