Basics of React.js Routing

React JSJavascript LibraryFront End Technology

Some basics of react routing

React-router is the main library and react-router-dom and react-router-native are the environment specific libraries. React-router-dom is used in browser based web applications generally. react-router-native is used in mobile based applications which can be developed using react-native.

To install it use command npm install –save react-router-dom

There are two types of router in case of web applications.

  • BrowserRouter
  • HashRouter

The difference between the two router types are visible in the way they formulate the URLs.

e.g. => BrowserRouter

e.g. => HashRouter (uses hash in it)

BrowserRouter is more popular and it uses html5 history API to keep track of locations.

HashRouter supports the legacy old browsers which do not support the html5 history API's.

JavaScript History API: It helps in keeping track of navigations, history stack, persists location state between sessions. Components create the history object that keeps the track of current location using history.location

History.push() is invoked whenever we click on Link component. If we click on Redirect component, history.replace is called. Similarly, history.go back and history.goForward are used to navigate back and forth in history stack.

Route component is the main in router which if matched will display the provided component in page. exact=true is added on route path if url has be to matched exactly. Route has render attribute which handle inline rendering. Render expects a function that returns an element if the path matches completely.

Link component is the anchor tag used to navigate between pages without reloading the page.

path attribute on the route component uses path-to-RegExp library to convert a string into regular expression . current location will be matched with it.

once we match the path given on route component and current location on the browser, a match object will be created with below information for further uses −

match.path=>A string containing the routs path value.

match.url=> the matched part of the url in browser.

match.isExact=> it’s a Boolean value.

switch − the benefit of using switch is it will return the first matched route and discard the others.

Without switch, all the path that matches will be rendered. Example is path /player and /player/1 both will be rendered if we have url like /player in browser. Switch avoid the multiple path matching. It will return the first match.

Example basic

<Route exact path="/" component={MainPage}/>
<Route path="/users" component={Users}/>
<Route path="/login" component={Login}/>
<Route path="/customers" component={Customers}/>
Published on 04-Sep-2019 12:08:13