Home > Software design >  How can I change routes correctly in react?
How can I change routes correctly in react?

Time:11-16

when I move to another route page changes url but not load however after reloading page it works, this is my App.js and index.js

import { Route, Routes } from 'react-router-dom' 
import Home from './components/Home' 
import About from './components/About' 
import Contact from './components/Contact' 
import Layout from './components/Layout' 
import Skills from './components/Skills' 
import Portfolio from './components/Portfolio' 
import './App.scss'

function App() { 
return ( <> 
<Routes> 
<Route path="/" element={<Layout />}> 
<Route path="/portfolio" element={<Portfolio />} /> 
<Route index element={<Home />} /> 
<Route path="about" element={<About />} /> 
<Route path='/skills' element={<Skills/>} /> 
<Route path="/contact" element={<Contact />} /> 
</Route> 
</Routes> 
</> ) 
} 
export default App
import React from 'react'
import ReactDOM from 'react-dom'
import reportWebVitals from './reportWebVitals'
import { BrowserRouter } from 'react-router-dom'
import App from './App'
import './index.css'

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
)

reportWebVitals()

solve the problem and be able to change pages quickly

CodePudding user response:

welcome to Stack Overflow. It would have been of great help if you have also mentioned what version of react-router-dom and react itself that you're using. The problem you are facing has been asked before which you can find here. Please refer to the question posted previously as there are tons of answers which might be helpful in solving your issue. Hope it helps.

CodePudding user response:

I see that, this is how your route is setup.

import { Route, Routes } from 'react-router-dom' 
import Home from './components/Home' 
import About from './components/About' 
import Contact from './components/Contact' 
import Layout from './components/Layout' 
import Skills from './components/Skills' 
import Portfolio from './components/Portfolio' 
import './App.scss'

function App() { 
  return ( 
    <> 
      <Routes> 
        <Route path="/" element={<Layout />}> 
          <Route path="/portfolio" element={<Portfolio />} /> 
          <Route index element={<Home />} /> 
          <Route path="about" element={<About />} /> 
          <Route path='/skills' element={<Skills/>} /> 
          <Route path="/contact" element={<Contact />} /> 
      </Route> 
    </Routes> 
  </> 
  ) 
} 
export default App

Your other routes are nested inside of your home route which calls Layout /> element.

So inside your <Layout /> component, call <Outlet /> as a child component. Please refer this link to understand hoe <Outlet /> works

Basically <Outlet /> works like props.children, but for routes, so here it should render child routes nested inside /

  • Related