0

I am trying to keep the language always in the route of my app like this: http://localhost:5173/en/ so if I go to this address http://localhost:5173, it should directly redirect to http://localhost:5173/en/ or http://localhost:5173/fr/ depending on the language on the context variable.

I am using React js v:18.2.0, React-router-dom v:6.4.1 and Vite v:3.1.0

Routepage:

import {
  Routes,
  Route,
} from "react-router-dom";
import Auth from "../pages/Auth.jsx";

const AppRoutes = () => {
  return (
    <Routes baseName="/">
        <Route path=":lang/">
            <Route path="authentification" element={<Auth/>} />
        </Route>
    </Routes>
  );
}

export default AppRoutes;

app.js:

import AppRoutes from "./routes";
import Footer from "./components/footer/Footer.jsx";
import {useContext} from "react";
import {AppContext} from "./context/AppContext.jsx";
import "./assets/styles/app.css";

function App() {
    const {lang, setLang} = useContext(AppContext)

    return (
        <div className="App">
            <AppRoutes />
            <Footer lang={lang} setLang={setLang}/>
        </div>
    )
}

export default App
  • 1
    redirect to the corresponding page when the language is changed – nullptr Nov 08 '22 at 13:40
  • The problem is not the redirection after the language change, is there a way that when I go this address: `http://localhost:5173`, the app automatically should add `/lang`, or this example: `http://localhost:5173/home` it should become automatically `http://localhost:5173/en/home` – ANASS OULED BEN TAHAR Nov 08 '22 at 13:43

1 Answers1

1

Use this pattern to redirect: How can I redirect in React Router v6?

In your case the redirect route should look like this:

<Route path="/" element={<Navigate to={`/${lang}`} replace />} />

Or path="*" if you want to catch all fallbacks.

Bar
  • 1,334
  • 1
  • 8
  • 21
  • Thank you, this fixed 80% of the problem now the language is added to the path but for a costume URL, it still needs something to change like when I write this URL `http://localhost:5173/authentification` it does not add `/fr/` to the path like this `http://localhost:5173/fr/authentification`. Is there a way to do that ? – ANASS OULED BEN TAHAR Nov 08 '22 at 14:07