Search code examples
javascriptreactjstypescript

I cant put Navbar on main.jsx on react


I'm currently learning React and I have this code on my main.jsx:

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

If I put the Navbar component here, it is giving me this error on console:

Uncaught TypeError: React2.useContext(...) is null

My Navbar Component

import React from 'react'
import { Link } from 'react-router-dom'

const Navbar = () => {
    return (
        <div>
            <Link to='/'>Home</Link>
            <br />
            <Link to='/dashboard'>Dashboard</Link>
            <br />
            <Link to='/contact'>Contact</Link>
        </div>
    )
}

export default Navbar

I can use Navbar on other components if I put it there but not on main.jsx. What Im trying to do basically is add the Navbar component to all the pages. Do that is why I added it there.

Any help would be appreaciated.


Solution

  • The issue you're encountering is likely due to the order of your component rendering and the context usage within your RouterProvider. When the Navbar component is rendered outside of the RouterProvider, it might not have access to the necessary context provided by the router.

    To resolve this, you can structure your app to ensure the Navbar has access to the router context. One common approach is to include the Navbar inside the component tree that the RouterProvider manages.

    Create a new file called Layout.jsx:

    import { Outlet } from 'react-router-dom'
    import Navbar from './Navbar'
    
    const Layout = () => {
        return (
            <div>
                <Navbar />
                <Outlet />
            </div>
        )
    }
    
    export default Layout
    

    Ensure your router configuration uses the Layout component:

    import ReactDOM from 'react-dom/client'
    import { createBrowserRouter, RouterProvider } from 'react-router-dom'
    import Layout from './Layout'
    import Home from './Home'
    import Dashboard from './Dashboard'
    import Contact from './Contact'
    
    const router = createBrowserRouter([
        {
            path: '/',
            element: <Layout />,
            children: [
                { path: '/', element: <Home /> },
                { path: '/dashboard', element: <Dashboard /> },
                { path: '/contact', element: <Contact /> },
            ],
        },
    ])
    
    ReactDOM.createRoot(document.getElementById('root')).render(
        <React.StrictMode>
            <RouterProvider router={router} />
        </React.StrictMode>,
    )