Hello there! This is the part of the tutorial where we make navigation magic ✨ happen.
In order to start, we first need to add some dependencies to our project with npm i react-router-dom @types/react-router-dom
.
If you remember, in our Menubar component we have everything set up so we could navigate between two links: /
for Home and /dates
for Tour Dates.
Let's create those.
In your src folder, create a Pages folder and inside create two files: Home.tsx
and TourDates.tsx
. We're using the .tsx
extension instead of the .ts
because the first one will allow us to use JSX.
For now, I'll leave both components really simple but you can go and add whatever you want on them.
import React from 'react'; | |
const Home: React.FC = () => { | |
return ( | |
<div className="container mx-auto"> | |
<div className="font-bold text-white">You are home</div> | |
</div> | |
); | |
}; | |
export default Home; |
import React from 'react'; | |
const TourDates: React.FC = () => { | |
return ( | |
<div className="container mx-auto"> | |
<div className="text-white">Tour Dates go here</div> | |
</div> | |
); | |
}; | |
export default TourDates; |
Great, now we have our two components all typed up and pretty. Now, we have to create a Routes.tsx
where we place all of our preferred routes.
In this case, our Routes.tsx
would look something like this.
import React from 'react'; | |
import { Switch, Route } from 'react-router-dom'; | |
import TourDates from './pages/TourDates'; | |
import Home from './pages/Home'; | |
const Routes: React.FC = () => ( | |
<Switch> | |
<Route exact path="/" component={Home} /> | |
<Route path="/dates" component={TourDates} /> | |
</Switch> | |
); | |
export default Routes; |
And finally, we have to make sure we add our Router component to make everything happen in App.tsx
.
import React from 'react'; | |
import './App.css'; | |
import { BrowserRouter as Router } from 'react-router-dom'; | |
import Menubar from './components/Menubar'; | |
import Banner from './components/Banner'; | |
import Footer from './components/Footer'; | |
import Routes from './Routes'; | |
const App: React.FC = () => { | |
return ( | |
<div className="App"> | |
<Router> | |
<Menubar /> | |
<Banner BannerImg="https://wallpaperset.com/w/full/0/7/f/32861.jpg" AltImg="The 1975 BW banner" /> | |
<Footer /> | |
<Routes /> | |
</Router> | |
</div> | |
); | |
}; | |
export default App; |
And ✨ that's it! You can now go back and forth between \
and \dates
in your Menubar.
I hope you found this helpful, stay safe and please remember to take a break.
Got something to add? Please feel free to reach out for any question, comment, meme or dog photos swap.
Top comments (0)