{"id":15850,"date":"2020-12-18T09:59:16","date_gmt":"2020-12-18T09:59:16","guid":{"rendered":"https:\/\/www.bacancytechnology.com\/blog\/?p=15850"},"modified":"2024-06-06T04:46:56","modified_gmt":"2024-06-06T04:46:56","slug":"guide-to-react-router-hooks","status":"publish","type":"post","link":"https:\/\/www.bacancytechnology.com\/blog\/guide-to-react-router-hooks","title":{"rendered":"A Beginner\u2019s Guide to React Router Hooks (Fundamentals of Routing in React)"},"content":{"rendered":"<p><strong>Quick Summary:<\/strong><\/p>\n<p><em>If you are planning to create a multipage React website and want to leverage all the perks of the React library, then I have created this hands-on guide to get your hands on React Routing with Router hooks. Let\u2019s go through this React Router Hooks tutorial and start learning!<\/em><\/p>\n<style>\np{\n   width:100%;\n}\n.post-content p img {\n    margin-bottom: 0 !important;\n}\n.text-orange,.text-orange> strong{\ncolor: #ec6100 !important;\nfont-weight: 700;\n}\n.border-box{\npadding: 12px;\nborder: 1px solid #000;\nmargin-bottom: 16px;\n}\n.border-div{border: 1px solid #000; padding: 22px; text-align: center; margin-bottom: 32px;}\n\t\t.border-bottom{\n\t\t\tborder-bottom: 1px solid #000;\n\t\t\ttext-align: center;\n\t\t\tdisplay: inline-block;\n\t\t}\n\t\t.border-div p{text-align: left;}\n\t\t.cust-list{padding: 0; text-align: left;}\n\t\t.cust-list li{padding-left: 32px; list-style: none}\n<\/style>\n<div class=\"border-div\">\n<h2 class=\"border-bottom\">Table of Index<\/h2>\n<p><a href=\"#1\"><strong>1. Introduction<\/strong> <\/a><\/p>\n<p><a href=\"#2\"><strong>2. What is React Routing? <\/strong><\/a><\/p>\n<p><a href=\"#3\"><strong>3. How to install react-router-dom?<\/strong><\/a><\/p>\n<p><a href=\"#4\"><strong>4. React Router: Fundamentals<\/strong><\/a><\/p>\n<p><a href=\"#5\"><strong>5. What is Dynamic Nested Routing?<\/strong><\/a><\/p>\n<p><a href=\"#6\"><strong>6. Router Hooks<\/strong><\/a><\/p>\n<p><a href=\"#7\"><strong>7. Conclusion<\/strong><\/a><\/p>\n<\/div>\n<h2 id=\"1\">Introduction<\/h2>\n<p>ReactJS is a front-end library based on Javascript, which helps us to create the user interface at our ease. And for managing the navigation of a multipage website, we\u2019ll be needing a third-party library like React Router.<br \/>\nThus, in this <a href=\"https:\/\/reactrouter.com\/\" target=\"_blank\" rel=\"noopener\">React Router<\/a> tutorial, we\u2019ll dig deep and understand routing in React.<\/p>\n<h2 id=\"2\">What is React Routing? <\/h2>\n<p>React Routing is a process of showing various pages on their respective URL. Users can have the liberty to navigate the pages by manually writing the URL or clicking the element. You need to install the react-router library to enable the routing in the React application. <\/p>\n<p><strong>React Router library provides three packages: <\/strong><\/p>\n<pre>\r\n<strong>react-router, \r\nreact-router-dom, \r\nand react-router native. <\/strong>\r\n<\/pre>\n<p>The react-router offers you the core functionality; react-router-dom and react-router-native are dependent on your projects\u2019 environment. One should use react-router-dom for website development and  React-router-native for mobile application development. <\/p>\n<h2 id=\"3\">How to install react-router-dom?<\/h2>\n<p>For installing React Router, you can use npm or yarn and run the following commands.<\/p>\n<pre>\r\nyarn add react-router-dom\r\n          OR\r\nnpm install react-router-dom\r\n<\/pre>\n<p>We have done the installation of the router successfully! Let\u2019s move ahead to get some knowledge regarding the basics of React Router.<\/p>\n<h2 id=\"4\">React Router: Fundamentals<\/h2>\n<p><strong>Router Component <\/strong><\/p>\n<p>We have to wrap our < App > component with <Router> component. As far as this is a website development, we can use either BrowserRouter Component or Hash Component. We will be using the BrowserRouter Component here. <\/p>\n<p>So, let\u2019s wrap the < App > component by importing the <Router> component from react-router-dom.<\/p>\n<pre>\r\n\/\/ \/src\/index.js\r\nimport React from \"react\";\r\nimport ReactDOM from \"react-dom\";\r\nimport App from \".\/App\";\r\nimport { BrowserRouter as Router } from \"react-router-dom\";\r\n\r\nReactDOM.render(\r\n  < Router >\r\n    < App \/ >\r\n  < \/Router >,\r\n  document.getElementById(\"root\")\r\n);\r\n<\/pre>\n<p>By this, we can apply the routing to our entire application. <\/p>\n<p>You are free to use BrowserRouter directly. I prefer to write it like this. The code written above will create the history object for the component.<\/p>\n<p>Every < Router > component written for wrapping a parent component (here < App > component) will generate the stack of previous locations and keep the record of the current location (history.location).<\/p>\n<p>Whenever the current location changes, the view re-renders, and you can see navigation between the pages. <\/p>\n<p>There must be a question about how does the current location change?<br \/>\nOr what makes it update the current location?<\/p>\n<p>Here is the answer, the history object consists of these two methods- history.push and history.replace.           <\/p>\n<p>On clicking the <Link> component history.push will invoke and < Redirect > component history.replace.<\/p>\n<p><strong>Link and Route Component<\/strong><\/p>\n<p>< Route > component is considered as an essential component in React Router. Its function is to render the UI whose current location matches the path (it is a prop under the Route component) of the route. <\/p>\n<p>< Link > component is used for navigating between the pages. We can compare it to the < a > tag of the HTML; the only difference is that < a > refreshes the page, which we don\u2019t need. Thus, we will use < Link > for navigating without refreshing the page.<\/p>\n<p>Okay, so I believe we are good till here. Great! Let\u2019s move ahead and make an application for the react-router example.<\/p>\n<pre>\r\n\r\n\/\/ \/src\/App.js\r\n\r\nimport React from \"react\";\r\nimport { Link, Route, Switch } from \"react-router-dom\";\r\n\r\nconst Home = ( ) => (\r\n   < h2 >This is the Home page< \/h2 >\r\n);\r\n\r\nconst About = ( ) => (\r\n    < h2 >This is an About page< \/h2 >\r\n);\r\n\r\nconst Contact = ( ) => (\r\n     < h2 >This is the Contact Page < \/h2 >\r\n);\r\n\r\nconst Products = ( ) => (\r\n    < h2 >This is the Products Page < \/h2 >\r\n);\r\n\r\nexport default function App() {\r\n  return (\r\n    < div >\r\n      < nav >\r\n         < ul >\r\n          < li >\r\n            < Link to=\"\/\" >Home< \/Link >\r\n          < \/li >\r\n          < li >\r\n            < Link to=\"\/about\" >About< \/Link >\r\n          < \/li >\r\n          < li >\r\n            < Link to=\"\/contact\" >Contact< \/Link >\r\n          < \/li >\r\n \t\t< li >\r\n            < Link to=\"\/products\">Products< \/Link >\r\n          < \/li >\r\n        < \/ul >\r\n      < \/nav >\r\n\r\n      { \/* when the path prop will match the current URL these components will render  *\/}\r\n      < Route path=\"\/\" > <Home\/ >< \/Route >\r\n      < Route path=\"\/about\" >< About\/ >< \/Route >\r\n      < Route path=\"\/contact\" >< Contact\/ >< \/Route >\r\n < Route path=\"\/products\" >< Products\/ >< \/Route >\r\n    < \/ div >\r\n  );\r\n}\r\n\r\n<\/pre>\n<p>Here we have four components &#8211; Home, About, Contact, and Products with their respective routes ( URL) \/home, \/about, \/contact, and \/products. The < Route > components consist of the logic for rendering the pages. < Link > components can be said as the < a > tag and are used for navigation. Whenever the prop path changes and matches the current URL, the matching route\u2019s component renders. <\/p>\n<p>Assume I\u2019m on the Home page so that the prop path would be \/home.<\/p>\n<p>Now further, I clicked the About link. So, directly the prop path would change to \/about from \/home. Hence, it will check the < Route > component\u2019s logic and render the < About \/ > component.<\/p>\n<p>I have written the code in the file App.js, but as the components exceed more code lines, I\u2019ll create separate components for each.<\/p>\n<p>There\u2019s a problem with this routing, though. Even if we switch the pages and click the link, we will always see the Home page. Whenever React Router checks its prop path, it will redirect to the component which is starting with  \/  and thus it will always display the Home page because its path is    \/  Assume I clicked the Products page. Now I\u2019ll see both the Home page and Products page because  \/  matches both  \/  and \/products.<\/p>\n<p>To overcome this default behavior of react routing, we can use the prop exact in the < Route > component. Rewrite the < Route > component for the Home page.<\/p>\n<pre>\r\n  < Route path=\"\/\" exact >< Home \/ >< \/Route >\r\n<\/pre>\n<p>By updating the code as above, the Home page will render when  it matches the exact route, i.e.,  \/    <\/p>\n<p>We are done with the necessary explanation with a simple example of react routing. Now, assume that we have sub-categories of the products, i.e., product_one and product_two; how will we write the logic for its routing? In such a case, where we have sub-categories, we tend to use nested routing. Our next topic of the react router tutorial is Dynamic Nested Routing; let\u2019s see what it has.<\/p>\n<h2 id=\"5\">What is Dynamic Nested Routing?<\/h2>\n<p>For having your hands on Dynamic Nested Routing, we should first know <Route> thoroughly. < Route > will render a component if the path will match or null if it doesn\u2019t. The documentation of React Router states that &#8211;<\/p>\n<p>The recommended method of rendering something with a <Route> is to use children elements. There are, however, a few other methods you can use to render something with a <Route>. These are provided mostly for supporting apps that were built with earlier versions of the router before hooks were introduced.<\/p>\n<p>So let\u2019s discuss those methods-<\/p>\n<ul class=\"bullets\">\n<li><strong>component:<\/strong> On using <strong>component<\/strong>, the router will create the React element, using React.createElement; whenever the URL will match, it will render the component. If you give a function that will return a component, it will create a new component at every render rather than updating it.<\/li>\n<pre>\r\n< Route path=\"\/products\" component={Products} \/ >\r\n<\/pre>\n<li><strong>render:<\/strong> On using <strong>render<\/strong>, the issue of remounting the component rather than updating it will be solved, as mentioned above. It allows inline rendering.<\/li>\n<pre>\r\n< Route path=\"\/products\" render={() => < Products \/ >} \/ >\r\n<\/pre>\n<li><strong>children:<\/strong> In some cases, you want to render something irrespective of whether the patch matches or not; at that time, you should prefer <strong>children<\/strong>.<\/li>\n<\/ul>\n<p>So, this was the overview of how <Route> manages to render the components. Let\u2019s learn about how to implement Dynamic Nested Routing.<\/p>\n<p>Remember I gave you the scenario above for the sub-categories of products; we will take that as an example and understand the nested routing.<\/p>\n<pre>\r\n\r\n\/\/ \/src\/App.js\r\n\r\nimport React from \"react\";\r\nimport { Link, Route, Switch } from \"react-router-dom\";\r\nimport Products from \".\/Products\";\r\n\r\nconst Home = () => (\r\n   < h2 >This is the Home page< \/h2 >\r\n);\r\n\r\nconst About = () => (\r\n    < h2 >This is an About page< \/h2 >\r\n);\r\n\r\nconst Contact = () => (\r\n    < h2 >This is the Contact Page < \/h2 >\r\n);\r\n\r\nexport default function App() {\r\n  return (\r\n    < div >\r\n      < nav >\r\n        < ul >\r\n          < li >\r\n            < Link to=\"\/\" >Home< \/Link >\r\n          < \/li >\r\n          < li >\r\n            < Link to=\"\/about\" >About< \/Link >\r\n          < \/li >\r\n          < li >\r\n            < Link to=\"\/contact\" >Contact< \/Link >\r\n          < \/li >\r\n \t\t< li >\r\n            < Link to=\"\/products\" >Products< \/Link >\r\n          < \/li >\r\n         < \/ul >\r\n      < \/nav >\r\n\r\n      { \/* when the path prop will match the current URL these components will render  *\/}\r\n      < Route path=\"\/\" >< Home\/ >< \/Route >\r\n      < Route path=\"\/about\"><About\/ >< \/Route >\r\n      < Route path=\"\/contact\"><Contact\/ >< \/Route >\r\n < Route path=\"\/products\"><Products\/ >< \/Route >  \r\n    < \/ div >\r\n  );\r\n}\r\n\r\n<\/pre>\n<p>I created a separate component for the Products to make it neat and clean.<\/p>\n<p>Here\u2019s the code for Products.js<\/p>\n<pre>\r\n\r\n\/\/ src\/Products.js\r\n\r\nimport React from \"react\";\r\nimport { Link, Route, useParams, useRouteMatch } from \"react-router-dom\";\r\n\r\nconst Item = ( ) => {\r\n  const { name } = useParams();\r\n\r\n  return (\r\n    < div >\r\n       < h3 >{name}< \/h3 >\r\n    < \/div >\r\n  );\r\n}\r\n\r\nconst Products = ( ) => {\r\n  const { url, path } = useRouteMatch();\r\n\r\n  return (\r\n    < div >\r\n      < ul >\r\n        < li >\r\n          < Link to={`${url}\/product-one`}>Product One<\/Link >\r\n        < \/li >\r\n        < li >\r\n          < Link to={`${url}\/product-two`} >Product Two<\/Link >\r\n        < \/li >\r\n       < \/ul >\r\n      < Route path={`${path}\/:name`} >\r\n        < Item\/ >\r\n      < \/Route >\r\n    < \/div >\r\n  );\r\n};\r\n\r\nexport default Products;\r\n\r\n<\/pre>\n<p>Here we have used the useRouteMatch hook in order to match URLs just like < Route >. As the documentation of React Routing have mentioned<\/p>\n<p><em>The useRouteMatch hook either:<\/em><\/p>\n<ul class=\"bullets\">\n<li>takes no argument and returns the match object of the current < Route ><\/li>\n<li>takes a single argument, which is identical to props argument of matchPath.<\/li>\n<\/ul>\n<p>If you have confusion regarding the useRouteMatch hook, you can console.log(useRouteMatch()) and clarify a few things.<\/p>\n<pre>\r\n< Route path={`${path}\/:name`} >\r\n  < Item \/ >\r\n< \/Route >\r\n<\/pre>\n<p>We will not hard code the routings; instead, we will try to attempt dynamic routing. We will use a variable within the prop path and  :product-name will be the path parameter that will find after \/products until we come across another forward slash. We will further use the useParams hook for accessing the value in the <Item> component.<\/p>\n<p>Okay, so far, we have covered Installation of React Router Dom, Basic and Dynamic Nested Routing in the react router tutorial, now it\u2019s time to move ahead with the Router Hooks.<\/p>\n<h2 id=\"5\">React Router Hooks<\/h2>\n<p>React Router hooks had made things a lot easier than before. Now the history, parameters, or location is accessible in a straightforward way. For React Router hooks, you must check that you are using the React version greater than or equal to 16.8. <\/p>\n<p>Here are the React Router hooks, which we will discuss further &#8211; <\/p>\n<ul class=\"bullets\">\n<li>useHistory<\/li>\n<li>useParams<\/li>\n<li>useLocation<\/li>\n<\/ul>\n<p><strong>useHistory<\/strong><\/p>\n<p>The useHistory will help you for accessing the history instance for navigating purposes. So, now there\u2019s no need to pull out the history from the prop; you can simply use the useHistory hook.<\/p>\n<pre>\r\nimport { useHistory } from \"react-router-dom\";\r\n\r\nconst Contact = () => {\r\nconst history = useHistory();\r\nreturn (\r\n  <>\r\n    < h2 >About< \/h2 >\r\n    < button onClick={() => history.push('\/') } >Go to homepage < \/button >\r\n  <\/>\r\n  )\r\n };\r\n<\/pre>\n<p><strong>useParams<\/strong><\/p>\n<p>The useParam will return an object of URL parameter\u2019s key\/value pairs without using the prop.<\/p>\n<pre>\r\n\r\nimport { BrowserRouter as Router, Route, Link, Switch, useParams } from \"react-router-dom\";\r\n\r\nexport default function App( ) {\r\n  const name = 'James Ruso'\r\n  return (\r\n   < Router >\r\n    < div >\r\n      < nav >\r\n        < ul >\r\n          < li >< Link to=\"\/\" >Dashboard<\/Link>< \/li >\r\n          < li >< Link to={`\/about\/${name}`} >About <\/Link>< \/li >\r\n        < \/ul >\r\n      < \/nav >\r\n    < Switch >\r\n      < Route path=\"\/\" exact component={Dashboard}\/ >\r\n      < Route path=\"\/about\/:name\"  component={About}\/ >\r\n    < \/Switch >\r\n    < \/div >\r\n< \/ Router >\r\n  );\r\n}\r\n\r\nconst About = ( ) => {\r\n  const { name } = useParams( )\r\n  return (\r\n  \/\/ props.match.params.name\r\n  <  >\r\n    { name !== 'James Ruso' ? < Redirect to= \" \/ \" \/> : null }\r\n     < h2 >About {name} < \/h2 >\r\n    < Route component={Contact} \/ >\r\n  < \/ >\r\n )\r\n};\r\n\r\n<\/pre>\n<p><strong>useLocation<\/strong><\/p>\n<p>The useLocation will return you the current location within the location object. <\/p>\n<pre>\r\n \r\nimport { useLocation } from \"react-router-dom\";\r\n\r\nconst About = ( ) => {\r\nconst { pathname } = useLocation();\r\n\r\nreturn (\r\n  < >\r\n    < h1>About< \/h1 >\r\n    < p >Here is the Current URL: {pathname}< \/p >\r\n  < \/ >\r\n  )h\t\r\n};\r\n \r\n<\/pre>\n<h2 id=\"8\">Conclusion:<\/h2>\n<p>I hope your purpose of landing on this blog post to learn about React router hooks has been served. If you are looking for assistance with React routers to create and navigate between different URLs or need support to manage the transition between views and redirects, then get in touch with us today to embrace the power of React Router with Router Hooks. We have expert ReactJS developers who are well-versed in offering top-of-the-line <a href=\"https:\/\/www.bacancytechnology.com\/hire-reactjs-developer\" target=\"_blank\" rel=\"noopener\">ReactJS development services<\/a>. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>Quick Summary: If you are planning to create a multipage React website and want to leverage all the perks of the React library, then I have created this hands-on guide to get your hands on React Routing with Router hooks. Let\u2019s go through this React Router Hooks tutorial and start learning! Table of Index 1. [&hellip;]<\/p>\n","protected":false},"author":151,"featured_media":32056,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"inline_featured_image":false,"_lmt_disableupdate":"no","_lmt_disable":"no","footnotes":""},"categories":[988],"tags":[],"coauthors":[2429],"class_list":["post-15850","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-react"],"acf":[],"modified_by":"Chandresh Patel","_links":{"self":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts\/15850","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/users\/151"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/comments?post=15850"}],"version-history":[{"count":0,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts\/15850\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/media\/32056"}],"wp:attachment":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/media?parent=15850"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/categories?post=15850"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/tags?post=15850"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/coauthors?post=15850"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}