- Understanding Routing
- Handling Routing in React with React Router Dom (https://reactrouter.com/web/guides/quick-start)
- Components of React Router Dom
- Link
- BrowserRouter
- Route
- Switch
- useLocation
- useParams
Routing refers to serving the end user with the content they want to see depending on the URL. A valid URL has this format : https://www.bigjara.com/users?q=adeleke+bright
https : protocol
wwww : sub-domain
bigjara.com : server address
/users : path
?q : Query params whose value is adeleke+bright
The user is searching for a particular user name "Adeleke Bright" at the path /users . We will need to be able to handle this. Knowing what to serve a user when a particular route is visited is what is known as routing . Before the advent of SPA (Single Page Applications ) , routing was mostly done on the server. The server handles routing for you , and serve the content the user is searching for . As we increasingly depend on building single page applications , we should be able to make our application work the way it used to work before now.
React Router Dom is the official library associated with React and React Native for routing. To get it , change into your project directory and issue the following command :
npm install react-router-dom
Assuming , I have an application with the following path and I want to add react routing :
- About
- Contact
- FAQ
- Login
- Signup On the root of my app , I will enclose everything within React Router using :
<BrowserRouter>
{/* Components and other Routes */}
</BrowserRouter>
If you do not enclose other react router portions within a Router , your application is going to crash. This is because routing mechanism begins from top to down. If you use a Link outside a BrowserRouter , you app is going to fail.
Assuming you have a Home Component which is your landing page. On the home section , you will have links that point to other pages (compononents) in your app. Before now , you will use the anchor tag for creating hyper linked documents. When using React Router , replace anchor tag with Link.
Normal Anchor Tag : <a href="\contact-us"> Contact Us
With Link : <\Link to="\contact-us"> Contact Us</Link>
You can use Link in a component without an accompanying BrowserRouter but ensure there is a BrowserRouter to start your routing in your app's main root. Most of the errors you faced were because you launched your app without the Router and Link was used inside other components