Create a Single Page App in SPFx using React Router Dom

Introduction

 
React Router Dom is a 3rd Party plugin for creating single-page apps in React. 
 
<Route>
 
This is the most important component in React Router. Its most basic responsibility is to render UI when its path matches the current URL.
 
Property sensitive refers to the URL parameter as being case sensitive
 
 <Link>
 
Provides navigation around your application.
 
<NavLink> 
 
A special version of the <Link> that adds styling attributes to the rendered element when it matches the current URL.
 
<BrowserRouter> 
 
Its replaces the URL with the path after the domain name of our URL. 
 
<HashRouter> 
 
Adds # string in the URL and appends the path with the URL.
 
<Redirect> 
 
Changes the URL value to another value, mainly used for Authentication
 
<switch> 
 
If any of the redirect URLs mismatch the relevant component,  a switch is used to maintain the error page(404) 
 
After 16.8 we can use React Hooks. The available hooks for React Router Dom are as follow:
  • useHistory
  • useLocation
  • useParams
  • useRouteMatch
Open a command prompt. Create a directory for the SPFx solution.
 
md spfx-SinglePageApp
 
Navigate to the above-created directory.
 
cd spfx-SinglePageApp
 
Run the Yeoman SharePoint Generator to create the solution.
 
yo @microsoft/sharepoint
 
Solution Name
 
Hit Enter to have the default name (spfx-SinglePageApp in this case) or type in any other name for your solution.
Selected choice - Hit Enter
 
Target for the component
 
Here, we can select the target environment where we are planning to deploy the client web part, i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
Selected choice - SharePoint Online only (latest)
 
Place of files
 
We may choose to use the same folder or create a subfolder for our solution.
Selected choice - Same folder
 
Deployment option
 
Selecting Y will allow the app to be deployed instantly to all sites and be accessible everywhere.
Selected choice - N (install on each site explicitly)
 
Permissions to access web APIs
 
Choose if the components in the solution require permission to access web APIs that are unique and not shared with other components in the tenant.
Selected choice - N (solution contains unique permissions)
 
Type of client-side component to create
 
We can choose to create a client-side web part or an extension. Choose the web part option.
Selected choice - WebPart
 
Web part name
 
Hit Enter to select the default name or type in any other name.
Selected choice - SpfxSinglePageApp
 
Web part description
 
Hit Enter to select the default description or type in any other value.
 
Framework to use
 
Select any JavaScript framework to develop the component. Available choices are - No JavaScript Framework, React, and Knockout.
Selected choice - React
 
The Yeoman generator will perform a scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.
 
Once the scaffolding process is completed, lock down the version of project dependencies by running the below command:
 
npm shrinkwrap
 
In the command prompt, type below command to open the solution in the code editor of your choice.
 
code .
 
NPM Packages Used,
 
On the command prompt, run below command.
  1. npm i react-router-dom  
in SpfxSinglePageApp.tsx 
  1. import * as React from 'react';  
  2. import styles from './SpfxSinglePageApp.module.scss';  
  3. import { Route, Link, Switch, BrowserRouter as Router,HashRouter } from 'react-router-dom';  
  4. import { ISpfxSinglePageAppProps } from './ISpfxSinglePageAppProps';  
  5. import PageNotFound from './PageNotFound';  
  6. import MyHome from './MyHomeComponent';  
  7. import MYDetails from './Details';  
  8. import MYDetailsWithParam from './DetailsWithParameter';  
  9. import MyRouteMatch from './MyRouteMatch';  
  10. import MyNestedRoute from './NestedRoute';  
  11.   
  12. export default class SpfxSinglePageApp extends React.Component<ISpfxSinglePageAppProps, {}> {  
  13.   public render(): React.ReactElement<ISpfxSinglePageAppProps> {  
  14.     return (  
  15.       <div className={ styles.spfxSinglePageApp }>  
  16.         <div className={ styles.container }>  
  17.         <HashRouter>    
  18.       <div>    
  19.         <nav className="navbar navbar-expand-lg navbar-light bg-light">    
  20.           <ul className="navbar-nav mr-auto">    
  21.             <li><Link to={'/'} className="nav-link"> MY Home </Link></li>    
  22.             <li><Link to={'/MyDetails'} className="nav-link">My Details</Link></li>    
  23.             <li><Link to={'/MyDetailsParam'} className="nav-link">My Details with Parameter</Link></li>   
  24.             <li><Link to={'/MyRoutemtch'} className="nav-link">My Route Match</Link></li>   
  25.             <li><Link to={'/MyRouteNewDetails'} className="nav-link">My Route New Details</Link></li>  
  26.           </ul>    
  27.         </nav>    
  28.         <hr />    
  29.         <Switch>    
  30.           <Route sensitive  exact path="/" component={MyHome} />    
  31.           <Route path="/MyDetails" component={(props) => <MYDetails text="Hello, " {...props} />} />    
  32.           {/*   
  33.             <Redirect from="/old-route" to="/new-route" /> 
  34.           <Route 
  35.             exact 
  36.             path="/props-through-render" 
  37.             render={props => ( 
  38.               <PropsPage {...props} title={`Props through render`} /> 
  39.             )} 
  40.           /> 
  41.            
  42.           */}  
  43.           <Route path="/MyDetailsParam/:name" component={MYDetailsWithParam} />   
  44.           <Route path="/MyRoutemtch/:name" component={MyRouteMatch} />  
  45.           <Route path="/MyRouteNewDetails" component={MyNestedRoute} />  
  46.           <Route component={PageNotFound} />    
  47.         </Switch>    
  48.       </div>    
  49.     </HashRouter>   
  50.         </div>  
  51.       </div>  
  52.     );  
  53.   }  
  54. }  
in PageNotFound.tsx
  1. import * as React from 'react';  
  2.     
  3. const PageNotFound = () => <h1>Requested Page Not Found</h1> ;   
  4.     
  5. export default PageNotFound;  
  6.   
  7. /*const SearchPage = ({ match, location }) => { 
  8.     return ( 
  9.       <p> 
  10.         <strong>Query Params: </strong> 
  11.         {location.search} 
  12.       </p> 
  13.     ); 
  14.   };*/  
in MyHomeComponent.tsx
  1. import * as React from 'react';    
  2. const MyHome = () => <h1>This is My Home Component</h1> ;       
  3. export default MyHome;  
 in Details.tsx
  1. import * as React from 'react';  
  2. export default class MYDetails  extends React.Component {    
  3.     constructor(props) {  
  4.         super(props);  
  5.       }  
  6.     public render(): React.ReactElement {  
  7.        // const {text, match: {params}} = this.props;  
  8.       console.log(this.props) ;  
  9.         return (  
  10.           <div>  
  11.           <h1>My Details Component</h1>  
  12.           </div>  
  13.         );  
  14.       }   
  15. }    
 in DetailsWithParameter.tsx
  1. import * as React from 'react';  
  2. import {useParams } from "react-router-dom";  
  3.    const MYDetailsWithParam = () => {  
  4.     let { name } = useParams();  
  5.     return <div>My Details With Paramter<br></br><b>{name}</b></div>;  
  6.    };  
  7.    export default MYDetailsWithParam;  
 in MyRouteMatch.tsx
  1. import {useRouteMatch,} from 'react-router-dom';  
  2. import * as React from 'react';  
  3. export default function MyRouteMatch(props) {  
  4.     let match = useRouteMatch("/MyRoutemtch/:name");  
  5.     return <div>My Details With Paramter{match.params.name}</div>;  
  6.   }  
NestedRoute.tsx
  1. import * as React from 'react';  
  2. import { Route, NavLink } from 'react-router-dom';    
  3. import {useParams} from 'react-router-dom';  
  4. //const MyDetails = ({ match }) => <p>{match.params.name}</p>;    
  5. const MyDetails = () => {  
  6.     let { name } = useParams();  
  7.     return <div>My Details With Paramter<br></br><b>{name}</b></div>;  
  8.    };    
  9. export default class MyNestedRoute extends React.Component {    
  10.     public render(): React.ReactElement {    
  11.         return (    
  12.             <div>    
  13.                 <p>Contact Us Component</p>    
  14.                 <strong>Select contact name</strong>    
  15.                 <ul>    
  16.                     <li><NavLink to="/MyRouteNewDetails/Madhan">Madhan</NavLink></li>    
  17.                     <li><NavLink to="/MyRouteNewDetails/Thurai">Thurai</NavLink></li>    
  18.                 </ul>    
  19.                 <Route path="/MyRouteNewDetails/:name" component={MyDetails}></Route>    
  20.             </div>    
  21.         );    
  22.     }    
  23. }    
  24.     
 Here, I am using Default Route, Route for Error Component, Route With Parameters and Nested Routes
 
Passing Route props to Class Components via Component prop or using Render prop,for hook we need not to pass
  1. <Route exact  path="/props-through-render"  render={props => (  <PropsPage {...props} title={`Props through render`} />  )}  />  
  2.   
  3. (or)  
  4.   
  5. <Route path="/props-through-render" component={(props) => <PropsPage text="Hello, " {...props} />} />  
Where exact refers strictly match with the path
 
Path -->The URL path where you want to render your component.
 
Sample Output for Router Props 
 
Single Page App In Spfx Using React-router-dom
 
Sample Output for Nested Component
 
Single Page App In Spfx Using React-router-dom
 
Sample Output without Parameter
 
Single Page App In Spfx Using React-router-dom
 
Sample Output with Parameter 
 
Single Page App In Spfx Using React-router-dom
 
Hence, we have seen some samples for React Router in SPFx. In upcoming articles, I will explain more deeply. Happy Coding :)