Home > database >  Route in Reactjs
Route in Reactjs

Time:12-28

I have two component ContentPage and MenuBar I want ContendPage change base on route and MenuBar will not change, my code:

import logo from './logo.svg';
import './style/App.css';
import MenuBar from './component/layout/MenuBar'
import ContentPage from './component/layout/ContentPage';
import { Router } from 'react-router';


function App() {
  return (
    <div className="App">
      <Router>
        <MenuBar/>
        <ContentPage/>
      </Router>
    </div>
  );
}

export default App;

My MenuBar code:

import React from 'react';
import { Link } from 'react-router-dom';
import '../../style/layout/menu-bar.css'

function MenuBar(props) {
  return <div className='MenuBar'>
    <button><Link to = "/page1">Page 1</Link></button>// have some button to click and and change contend in ContendPage component
  </div>;
}
  
  export default MenuBar;

My Contend component:

import React from 'react';
import { BrowserRouter as Router, Route} from 'react-router-dom';
import CrudPage from '../page/CrudPage';
import  '../../style/layout/content-page.css'

function ContentPage(props) {
    return <div className='ContentPage'>
        //Contend will be change in this scope
    </div>;
}

export default ContentPage;

Anyone have suggestion?

CodePudding user response:

you have to take your menuBar out of router, like so:


function App() {
  return (
    <div className="App">
      <MenuBar/>
      <Router>
        <ContentPage/>
      </Router>
    </div>
  );
}

CodePudding user response:

It's not right. You have to define routes like this.

<div className="App">
     <MenuBar />
     <Routes>
       <Route path="/content" element={<ContentPage />} />
     </Routes>
 </div>

if your content route page is dynamic you have to do this:

<Routes>
   <Route path="/content/:id" element={<ContentPage />} />
</Routes>

then get the params(id) in the content component.

You can check the doc here.

  • Related