Search code examples
javascriptreactjsreact-routerreact-router-dom

React multiple components nested routing


I have created a multiple components in one .js file For e.g: Under Home.js file --> blog, about and contact class components

Home.js File

So now I want to render all the components(blog, about, contact) under home. App.js file where I want to route

I am not sure what to add in element or any other options are there.

I tried with the <Home /> but it's not the solution.


Solution

  • If you want the Home component to remain mounted and also render the Blog, About, or Contact component as a layout route then Home should be updated to render an Outlet component for the nested routes to render their content into.

    Example:

    import { Outlet } from 'react-router-dom';
    
    export const Home = () => {
      return (
        <div>
          This is home page
          <Outlet />
        </div>
      );
    };
    
    export const Blog = () => <div>Blog Content</div>;
    export const About = () => <div>About Content</div>;
    export const Contact = () => <div>Contact Details</div>;
    
    <BrowserRouter>
      <HeaderP />
      <Routes>
        <Route path="/" element={<Home />}>
          <Route path="blog" element={<Blog />} />
          <Route path="about" element={<About />} />
          <Route path="contact" element={<Contact />} />
        </Route>
      </Routes>
    </BrowserRouter>
    

    If you just want each component rendered alone on its own page then unnest the blog, about, and contact routes.

    export const Home = () => <div>This is home page</div>;
    export const Blog = () => <div>Blog Content</div>;
    export const About = () => <div>About Content</div>;
    export const Contact = () => <div>Contact Details</div>;
    
    <BrowserRouter>
      <HeaderP />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/blog" element={<Blog />} />
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
      </Routes>
    </BrowserRouter>