React router in SPFx

This article provides steps to use the react-router in the SharePoint Framework (SPFx) web part, generally, React Router keeps your UI in sync with the URL. It has a simple API with powerful features like lazy code loading, dynamic route matching, and location transition handling built right in. Make the URL your first thought, not an after-thought.  

  

Create a new web part project

Open power shell and run following comment to create a new web part by running the Yeoman SharePoint Generator

yo @microsoft/sharepoint

When prompted:

Enter the webpart name as your solution name, and then select Enter.
Select Create a subfolder with solution name for where to place the files.
Select Y to allow the solution to be deployed to all sites immediately.
Select N on the question if solution contains unique permissions.
Select WebPart as the client-side component type to be created.

The next set of prompts ask for specific information about your web part:

Enter your web part name, and then select Enter.
Enter your web part description, and then select Enter.
Select React framework as the framework you would like to use, and then select Enter.

Start Visual Studio Code (or your favorite code editor) within the context of the newly created project folder.

cd .\web part name\
code .

Install the library and required dependencies

npm install react-router-dom --save

Root Component

We define the router in the root react component, here we import all the react components which are we going to use for navigation, We using a hash router this is much safer for SPfx, we can define then place where the child components have to load by place the HashRouter tag position,  

import * as React from 'react';
import styles from './SpfxReactRouter.module.scss';
import { ISpfxReactRouterProps } from './ISpfxReactRouterProps';
import SpfxCustomersFiles from './SpfxCustomersFiles';
import SpfxCustomers from './SpfxCustomers';
import SpfxCustomerDetails from './SpfxCustomerDetails';
import { HashRouter, Route } from "react-router-dom";
import { Nav, INavStyles, INavLinkGroup } from 'office-ui-fabric-react/lib/Nav';
import { Stack, IStackTokens } from 'office-ui-fabric-react/lib/Stack';

const navStyles: Partial<INavStyles> = { root: { width: 300 } };
const stackTokens: IStackTokens = { childrenGap: 40 };

const navLinkGroups: INavLinkGroup[] = [
  {
    name: 'React Components',
    links: [
      {
        key: 'Customers',
        name: 'Customers',
        url: '#/',
      },
      {
        key: 'CustomerDetails',
        name: 'Customer Details',
        url: '#/Customer/153',
      },
      {
        key: 'Customerfiles',
        name: 'Customer files',
        url: '#/CustomerFiles',
      },
    ],
  }
];


export default class SpfxReactRouter extends React.Component<ISpfxReactRouterProps, {}> {

  public render(): React.ReactElement<ISpfxReactRouterProps> {
    return (
      <div className={styles.spfxReactRouter}>
        <Stack horizontal tokens={stackTokens}>
          <Nav styles={navStyles} ariaLabel="Nav example similiar to one found in this demo page" groups={navLinkGroups} />
          <HashRouter>
            <Route path="/" exact component={SpfxCustomers}></Route>
            <Route path="/Customer/:id" component={SpfxCustomerDetails}></Route>
            <Route path="/CustomerFiles/" component={SpfxCustomersFiles}></Route>
          </HashRouter>
        </Stack>
      </div>
    );
  }
}

Child components

In the child components, we can get the id passed from the hashtag using props match, check below code for more details

import * as React from 'react';
import styles from './SpfxReactRouter.module.scss';
import { ISpfxReactRouterProps } from './ISpfxReactRouterProps';

export default class SpfxCustomerDetails extends React.Component<ISpfxReactRouterProps, {}> {

  public render(): React.ReactElement<ISpfxReactRouterProps> {
    return (
      <div className={styles.spfxReactRouter}>
        <h1>Selected Customer Id is <span style={{color:'green'}}>{this.props["match"]["params"]["id"]}</span></h1>
      </div>
    );
  }
}

also, we can just switch to the another component by just changing the hashtag

import * as React from 'react';
import styles from './SpfxReactRouter.module.scss';
import { ISpfxReactRouterProps } from './ISpfxReactRouterProps';




export default class SpfxCustomers extends React.Component<ISpfxReactRouterProps, {}> {

  public render(): React.ReactElement<ISpfxReactRouterProps> {
    return (
      <div className={ styles.spfxReactRouter }>
          <h1>Customers Component</h1>
          <h1><a href="#/Customer/153">Customer 153</a></h1>
          <h1><a href="#/Customer/154">Customer 153</a></h1>
          <h1><a href="#/Customer/155">Customer 153</a></h1>
          <h1><a href="#/Customer/156">Customer 153</a></h1>
      </div>
    );
  }
}

Deploy the solution

You’re now ready to build, bundle, package, and deploy the solution.

Run the gulp commands to verify that the solution builds correctly.

gulp build

Use the following command to bundle and package the solution.

gulp bundle --ship
gulp package-solution --ship

Browse to the app catalog of your target tenant and upload the solution package. You can find the solution package under the sharepoint/solution folder of your solution. It is the .sppkg file. After you upload the solution package in the app catalog. you can find and the web part anywhere across the tenant.

Sharing is caring!

If you have any questions, feel free to let me know in the comments section.
Happy coding!!!

Comments

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s