I am trying to implement a Router in my React app while following an online tutorial but my LandingPage
component does not display.
Router.tsx:
import {
BrowserRouter as Switch,
Route,
BrowserRouter,
} from "react-router-dom";
import LandingPage from "./components/LandingPage";
const Router = () => {
return (
<BrowserRouter>
<Switch>
<Route path="/" element={<LandingPage />} />
</Switch>
</BrowserRouter>
);
};
export default Router;
main.tsx:
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import Router from "./Router.tsx";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<Router />
</React.StrictMode>
);
LandingPage.tsx:
import React from "react";
const LandingPage: React.FC = () => {
return <h1>Welcome!!!</h1>;
};
export default LandingPage;
I tried to look online for any changes I might have to make for react-router-dom version 6.23.1 but I have the correct syntax. I tried to replace the path="/"
with index. I tried replacing React.StrictMode
in main.tsx
with a BrowserRouter
instead. Nothing has worked for me and I am confused. Does anyone know how I can fix this?
You imported a second BrowserRouter
and nested it under the first router, there should be an invariant error informing you as such, and there is no Routes
component.
Update the code to the following:
import {
BrowserRouter,
Routes, // <-- import Routes (acts like old v5 Switch)
Route,
} from "react-router-dom";
import LandingPage from "./components/LandingPage";
const Router = () => {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<LandingPage />} />
</Routes>
</BrowserRouter>
);
};
export default Router;