javascriptreactjsreact-routerreact-router-dom

I have started learning to create Routes in react but i am struck with a code where various contents of home page are not in a single component


As I stated that I have learned some basics of routing but there always a path defined "/" for home element whereas in my case I have many components of home page that is giving me a headache. I try to wrap them in app.jsx and then use them as home page but at both "http://localhost:5173" and "http://localhost:5173/about/" locations same app.jsx is rendering.

app.jsx

import Navbar from "./components/Navbar";
import HeroSection from "./components/HeroSection";
import FeatureSection from "./components/FeatureSection";
import Workflow from "./components/Workflow";
import Footer from "./components/Footer";
import Pricing from "./components/Pricing";
import Testimonials from "./components/Testimonials";
import { Outlet } from 'react-router-dom';

const App = () => {
  return (
    <>
      <Navbar />
      <div className="max-w-7xl mx-auto pt-20 px-6">
        <HeroSection />
        <FeatureSection />
        <Workflow />
        <Pricing />
        <Testimonials />
        <Footer />
        <Outlet />
      </div>
    </>
  );
};

export default App;

main.jsx

import React, { Children } from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import { RouterProvider, createBrowserRouter } from 'react-router-dom'
import App from "./App"
import About from './components/About'

const router = createBrowserRouter([
  {
    path: '/',
    element: <App />,
    children: [
      {
        path: '/about',
        element: <About />,
      }
    ]
  }
])

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>,
)

I am expecting to create dynamic route as stated


Solution

  • The issue is that you unconditionally render the "home page" content above all nested children route content.

    Refactor the code to move the "home page" content into an actual home page component and render it on an index route under App.

    Example:

    const Home = () => (
      <div className="max-w-7xl mx-auto pt-20 px-6">
        <HeroSection />
        <FeatureSection />
        <Workflow />
        <Pricing />
        <Testimonials />
      </div>
    );
    
    const App = () => {
      return (
        <>
          <Navbar />
          <Outlet />
          <Footer />
        </>
      );
    };
    
    import App from "./App"
    import Home from './components/Home';
    import About from './components/About';
    
    const router = createBrowserRouter([
      {
        element: <App />,
        children: [
          { index: true, element: <Home /> }
          { path: '/about', element: <About /> }
        ]
      }
    ]);