What I’m aiming for is when I click the sign up button is that it would go to the component SignUp
. But unfortunately it’s not routing or functioning.
App.js:
import React from "react";
import "./styles/App.css";
import Homepage from "./pages/homepage";
import { Routes, Route } from "react-router-dom";
export const App = () => {
return (
<>
<Routes>
<Route path="/" />
</Routes>
</>
)
<Homepage/>
};
export default App;
Body.js:
import React from "react";
import { BrowserRouter, Routes, Link, Route, Switch } from "react-router-dom";
import SignUp from "../pages/signUp";
const Body = () => {
return (
<div>
<BrowserRouter>
<button type="button" id="signup-btn">
<Link to="/signup">Sign up</Link>
</button>
<Switch>
<Route path="/signup" element={SignUp}/>
</Switch>
</BrowserRouter>
</div>
)
}
export default Body;
Any suggestions? Or should I rewrite my code where navbars are separated?
2
Answers
First, in your App.js file, make sure to import the
BrowserRouter
fromreact-router-dom
and wrap the entire application with it:Now, in your Body.js file, remove the unnecessary
<BrowserRouter>
element since it’s already used in App.js.Instead, use the
Link
component to navigate to the SignUp component:Assuming that the
HomePage
component inApp
is theBody
component from the second snippet you’ve a few things mixed up.Promote the
BrowserRouter
above theApp
component so it’s the sole routing context provider.From here you have a couple choices:
Render
Homepage
on the root"/"
route with an appended"*"
wildcard character so that descendent routes can also be matched and rendered.Remove the
Routes
and root"/"
route fromApp
and just renderHomePage
directly.The
Switch
is a RRDv5 component and was replaced by theRoutes
component. TheRoute
component’selement
prop takes aReact.ReactNode
, e.g JSX. I suggest also renaming the component fromBody
toHomePage
so there’s no future confusion.I think this is a good idea. A refactor may look something like the following: