The main function of this blog is to help me remember the process of building a multi page react app
What is react router
React router is short hand for a NPM package react-router-dom that allows developers like yourself to build out multi page application through a practice called client side routing. Typically servers handle web routing, react router gives the illusion of a normal web page.
getting started
after you have created your app using npm create-react-app double check if react-router-dom is installed with:
npm i react-router-dom
next you will need to import the following code into your index.js
import {BrowserRouter} from 'react-router-dom'
after you have imported browser router some modification will need to be made to the body of the file
the BrowserRouter tags need to wrap around the App component like so:
ReactDOM.render(
<React.StrictMode>
<BrowserRouter > // <-- here
<App />
</BrowserRouter> // <-- and here
</React.StrictMode>,
document.getElementById('root')
note: browser router is a parent component and can only have one child
This will also need to add this import to your App.js
import {Link, Switch, BrowserRouter, Route, Redirect} from 'react-router-dom'
next we will create the body of our app and for sake of ease we will only have two routes
<BrowserRouter>
<Switch>
<Route path="/home">
<Home />
</Route>
<Route path="/pathname">
<YourComponent />
</Route>
<Route path="/anotherpathname">
<YourOtherComponent />
</Route>
</Switch>
</BrowserRouter>
- the first thing thats happening in the code above is the implementation of the Browswer router tags, next we use the switch tags to which allows us to switch between different routes
- the routes are where we specify our path that will be differentiate the different pages in our app. Inside the rout you can store the component that you want to display on the path you specified in the Route tag
now we will go over and build the components that we specified in App.js
in all the components you will need to import the following:
import {Switch} from 'react-router-dom'
The general structure of your these components are all the same and will
function home() {
return (
<>
<h1>welcome Home!</h1>
<Link to="/pathname">your component</Link>
<Link to="/annotherpathname">your other component</Link>
</>
)
}
function YourComponent() {
return (
<>
<h1>welcome to YourComponent</h1>
<Link to="/home">home</Link>
<Link to="/pathname">other component</Link>
</>
)
}
function YourOtherComponent() {
return (
<>
<h1>welcome to YourOtherComponent</h1>
<Link to="/home">home</Link>
<Link to="/annotherpathname">your other component</Link>
</>
)
}
And there you have it, a basic functioning react app with multiple pages! you now have access to:
- /home
- /annotherpathname
- /pathname
Top comments (1)
You are not building a multi page app. It's SPA.