Hello I am currently struggling with 'react-router-dom' @6 Link element. Clicking the signup text belongs to the Link elements allows the browser url becomes localhost:5000 -> localhost:5000/signup but still Signup component doesn't appear. I have no idea where to correct my code.
import Form from './components/form';
import Comments from './components/comments';
import Header from './components/header';
import Signup from './components/signup';
import { useState } from 'react';
import { render } from 'react-dom';
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
import './styles/app.scss';
function App() {
const [ text, stateText ] = useState('');
const [ user, stateUser ] = useState({});
return (
<div className="App">
<Header />
<BrowserRouter>
<Routes>
<Route path="/comments" element={<Comments text={text} />} />
<Route path="/signup" element={<Signup />} />
<Route
path="/"
element={<Form text={text} stateText={stateText} user={user} stateUser={stateUser} />}
/>
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
the below one is header.js
import { BrowserRouter, Routes, Route, Router, Link} from 'react-router-dom';
const Header = () => {
return (
<div className="header_component">
<BrowserRouter>
<Link to="/signup">Signup</Link>
</BrowserRouter>
</div>
);
};
export default Header;
lastly, the one which is below is index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import Header from './components/header';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
reportWebVitals();
CodePudding user response:
The links in the Header
and the routes all need to be rendered within the same router. You only need one router per app to provide the routing context to all Link
, Routes
, Route
, Navigate
, Outlet
components, and all RRD hooks.
Move Header
into the Router
in App
and remove the Router
in the Header
component.
function App() {
const [ text, stateText ] = useState('');
const [ user, stateUser ] = useState({});
return (
<div className="App">
<BrowserRouter>
<Header />
<Routes>
<Route path="/comments" element={<Comments text={text} />} />
<Route path="/signup" element={<Signup />} />
<Route
path="/"
element={<Form text={text} stateText={stateText} user={user} stateUser={stateUser} />}
/>
</Routes>
</BrowserRouter>
</div>
);
}
...
const Header = () => {
return (
<div className="header_component">
<Link to="/signup">Signup</Link>
</div>
);
};