Home > Mobile >  When I apply react router to my app, it stops showing all the content
When I apply react router to my app, it stops showing all the content

Time:03-06

I'm trying to create an app with react router, but when I try to apply the react router, it instantly stops showing all the content. I'm using V5 so Switch should work but it doesnt

Here is the code:

import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";

export default function App() {
  return (
    <>
     <Router>
         <Switch>
        <Route exact path="/">
        <Main />
        </Route>
        <Route exact path="/form">
          <Form />
        </Route>
        </Switch>
      </Router>
    </>
);

CodePudding user response:

You need to first go to the index.js or main.jsx file and wrap your App component with BrowserRouter> component.

 <BrowserRouter>
    <App />
 </BrowserRouter>

or you can create routes here as the example below

<BrowserRouter>
  <Routes>
    <Route path="/" element={<App />} />
    <Route path="compOne" element={<Component1 />} />
    <Route path="compTwo" element={<Component2 />} />
  </Routes>
</BrowserRouter>

Now you can use routes by using Navlink or Link components.

CodePudding user response:

You have setup your routes, but you aren't rendering any components.

With React Router V6, simply instansiate a React component inside the element prop on each Route:

...
export default function App() {
  return (
    <>
     <Router>
         <Switch>
        <Route exact path="/" element={<Home />}>
        <Main />
        </Route>
        <Route exact path="/form" element={<Form />}>
          <Form />
        </Route>
        </Switch>
      </Router>
    </>
);

If you haven't already, I'd advice encapsulating each route into its own component to make this easier.

  • Related