Home > other >  React router doesn't work for some reason
React router doesn't work for some reason

Time:05-28

I'm working on my portfolio. I'm trying to put all components (Home, Skills, Projects, Contact) on one page, so I'm not planning to set routes for those component. However I want to set a route for project detail component, which I'll put a link on Projects component. I also want to set a route for 404 page.

I wrote the following code but it doesn't know ProjectDetail page when I access http://localhost:3000/projects. Can you give me advice how I can fix the problem?

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Home from './Home';
import Skills from './Skills';
import Projects from './Projects';
import ProjectDetail from './ProjectDetail';
import Contact from './Contact';
import Error from './Error';

const App = () => {
    return (
        <>
            <Router>
                <Home />
                <Skills />
                <Projects />
                <Contact />
                <Routes>
                    <Route path='/projects' element={<ProjectDetail />} />
                    <Route path='*' element={<Error />} />
                </Routes>
            </Router>
        </>
    );
};

export default App;

CodePudding user response:

I think you need to wrap all the components that u want in one page and put it on a route like this: <Route path="/" element={<OnePageApp/>}/>

After this i don't see any other errors.

Good Luck, I hope i have been able to help you

CodePudding user response:

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Home from './Home';
import Skills from './Skills';
import Projects from './Projects';
import ProjectDetail from './ProjectDetail';
import Contact from './Contact';
import Error from './Error';

const App = () => {
    return (
        <>
            <Router>
                <Home />
                <Skills />
                <Projects />
                <Contact />
                <Routes>
                    <Route path='/projects' element={ProjectDetail} />
                    <Route path='*' element={Error} />
                </Routes>
            </Router>
        </>
    );
};

export default App;
  • Related