Home > Enterprise >  react-router-dom v6 renders only default route
react-router-dom v6 renders only default route

Time:08-28

I'm starting a new project using React Router Dom v6 and I'm in trouble with one of the first steps: setting the routes for the App.

I just created two pages: AuthPage and DashboardPage and I would like to be able of rendering both of them if, from the browser, I navigate to:

  • localhost:PORT/ : should render DashboardPage
  • localhost:PORT/auth: should render AuthPage

but right no the only page rendered is DashboardPage even if I try to navigate to non-existing routes.

This is my code so far:

main.tsx

import { createRoot } from 'react-dom/client'
import { MemoryRouter as Router } from 'react-router-dom'
import { ThemeProvider } from '@mui/material/styles'
import { theme } from './theme'
import App from './App'

const root = createRoot(document.getElementById('root') as HTMLElement)

root.render(
  <ThemeProvider theme={theme}>
    <Router>
      <App />
    </Router>
  </ThemeProvider>
)

App.tsx

import { Route, Routes } from 'react-router-dom'
import AuthPage from './pages/AuthPage'
import DashboardPage from './pages/DashboardPage'
import NotFoundPage from './pages/NotFoundPage'
import { routes } from './routes'

function App() {
  return (
    <Routes>
      <Route path={routes.dashboard.url} element={<DashboardPage />} />
      <Route path={routes.auth.url} element={<AuthPage />} />
      <Route path={routes.notFound.url} element={<NotFoundPage />} />
    </Routes>
  )
}

export default App

routes.ts

export const routes = {
  auth: {
    url: '/auth'
  },
  dashboard: {
    url: '/'
  },
  notFound: {
    url: '*'
  }
}

CodePudding user response:

Use BrowserRouter instead of MemoryRouter :

import { createRoot } from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import { ThemeProvider } from '@mui/material/styles'
import { theme } from './theme'
import App from './App'

const root = createRoot(document.getElementById('root') as HTMLElement)

root.render(
  <ThemeProvider theme={theme}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </ThemeProvider>
)

CodePudding user response:

As I know, exact option doesn't supported in react-router v6. Try to use index option.

<Route path="/*">
  <Route index element={< DashboardPage />} />
  <Route path={routes.auth.url} element={<AuthPage />} />
  // ... other routes
</Route>
  • Related