Home > Net >  How to use / (slash), without using it as a path in React routing?
How to use / (slash), without using it as a path in React routing?

Time:10-07

A name of one item in my array is name for example: "apples/oranges?" and I use this name as an id so I can use it as a page route as well to render a different page and the slash is creating a problem with routing.

How can I use the slash simple as a text?

CodePudding user response:

Generally you cannot use a path segment value that contains the "/" path segment character, you'd need to replace the "/" character with a different character, i.e. change "apples/oranges" to "apples-oranges" so it could be assigned to a single path param.

The exception is Edit how-to-use-slash-without-using-it-as-a-path-in-react-routing

enter image description here

Example code:

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

const Home = () => {
  const { "*": name } = useParams();

  return (
    <>
      <h1>Home</h1>
      <div>Name: {name}</div>
    </>
  );
};

export default function App() {
  return (
    <div className="App">
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/apples">Apples</Link>
        </li>
        <li>
          <Link to="/oranges">Oranges</Link>
        </li>
        <li>
          <Link to="/apples/oranges">Apples/Oranges</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
      </ul>

      <Routes>
        <Route path="/*" element={<Home />} />
        <Route path="/about" element={<h1>About</h1>} />
      </Routes>
    </div>
  );
}

To avoid path collisions you might also consider "name spacing" them into a sub-route.

<Routes>
  ...
  <Route path="/name/*" element={<Home />} />
  <Route path="/about" element={<h1>About</h1>} />
  ... any other non-"/name" routes ...
</Routes>
  • Related