Mastering React Router: Navigating Your React Applications

Karnika Gupta
Women in Technology
4 min readSep 9, 2023
React

Introduction

React Router is a library in react that helps in building single-page applications (SPAs), providing smooth and dynamic navigation. In this blog, we’ll discuss about basic setup of react router to advanced navigation of your react applications which will make it easy and user-friendly.

1. Understanding of React Router:

React router is a library that helps in client-side navigation. It helps in rendering the components based on the route, maintains the history in browser and manage the URLs.

2. Installation and Setup:

In your terminal, write the following command to install the react router:

npm install react-router-dom

Note: Make sure you have npm installed before running the above command.

Basic setup in your App.jsx file:

import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

function App() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>

<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</div>
</Router>
);
}

export default App;

In the above code, Route defines the path where the component will be rendered. The path / will take you to the Home.jsx component. Link is used to navigate to the path by clicking on it.

3. Basic Routing:

There are 3 basic routing methods that you can use for navigation:

Route Component:

import { Route } from 'react-router-dom';

<Route path="/about" component={About} />

Navigating with Links:

import { Link } from 'react-router-dom';

<Link to="/about">About</Link>

Route Parameters:

<Route path="/user/:id" component={UserProfile} />

4. Nested Routing:

In this routing, nested routes can be created within components for complex layouts.

Nested Routes:

function Dashboard() {
return (
<div>
<h2>Dashboard</h2>
<Route path="/dashboard/profile" component={UserProfile} />
<Route path="/dashboard/settings" component={UserSettings} />
</div>
);
}

Route Render Props:

<Route
path="/dashboard"
render={() => (
<div>
<h2>Dashboard</h2>
{/* Render additional components */}
</div>
)}
/>

Dashboard.jsx has two nested routes i.e., /dashboard/profile and /dashboard/settings within the component and /dashboard is defined in the App.jsx .

5. Programmatic Navigation:

Redirect can be used in programmatic navigation to navigate to a specific route. Browser history can be manipulated using useHistory() .

Redirect:

import { Redirect } from 'react-router-dom';

// Inside a component...
if (someCondition) {
return <Redirect to="/login" />;
}

History Object:

import { useHistory } from 'react-router-dom';

let history = useHistory();
history.push('/new-route');

6. Route Guards and Authentication:

Private Routes protects routes with authentication using higher-order components and Route Guards helps in conditional navigation.

Private Routes:

function PrivateRoute({ component: Component, ...rest }) {
return (
<Route
{...rest}
render={(props) =>
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to="/login" />
)
}
/>
);
}

// Usage
<PrivateRoute path="/dashboard" component={Dashboard} />

Route Guards:

<Route
path="/admin"
render={() => {
return isAdmin ? (
<AdminPanel />
) : (
<Redirect to="/login" />
);
}}
/>

7. Advanced Routing Techniques:

Unmatched routes can be handled by wildcard routes. You can add navigation while navigating between routes. Routes can be dynamically loaded for improved performance.

Wildcards Routes:

<Route path="/user/*" component={UserProfile} />

Route Transition Animations:

import { CSSTransition } from 'react-transition-group';

<CSSTransition
in={true}
appear={true}
timeout={300}
classNames="fade"
>
<ComponentToShow />
</CSSTransition>

Lazy Loading Routes:

const LazyComponent = React.lazy(() => import('./LazyComponent'));

<Route path="/lazy" component={LazyComponent} />

8. URL Parameters and Query Strings:

Query Parameters:

// URL: /search?q=react
const searchQuery = new URLSearchParams(location.search).get('q');

URL Parameters:

// URL: /user/123
const userId = match.params.id;

9. React Router with Redux:

You can combine React Router with Redux for navigation and state management.

Integrating React Router with Redux:

import { connect } from 'react-redux';
import { push } from 'connected-react-router';

// Dispatching a navigation action
<button onClick={() => this.props.navigate('/dashboard')}>Dashboard</button>

Managing Router State in Redux:

// Reducer for router state
import { connectRouter } from 'connected-react-router';

const rootReducer = (history) =>
combineReducers({
router: connectRouter(history),
// Other reducers...
});

10. Server-Side Rendering with React Router:

Adding SSR to Your Application:

// In your server code...
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom';

const app = (
<StaticRouter location={req.url}>
<App />
</StaticRouter>
);

const content = renderToString(app);

Data Fetching in SSR Routes:

// In an SSR route component...
import { matchPath } from 'react-router-dom';

const match = matchPath(req.url, {
path: '/user/:id',
exact: true,
strict: false
});

if (match) {
const userId = match.params.id;
// Fetch data for the user with userId
}

11. Testing and Debugging:

Testing React Router:

import { MemoryRouter } from 'react-router-dom';

const renderWithRouter = (component) => {
return render(<MemoryRouter>{component}</MemoryRouter>);
};

// Usage in tests
const { getByText } = renderWithRouter(<MyComponent />);

Debugging Router Issues:

import { withRouter } from 'react-router-dom';

const MyComponent = withRouter(({ history }) => {
return (
<button onClick={() => history.push('/new-route')}>
Navigate
</button>
);
});

12. Best Practices:

Code Organization:

// Structure your routes and components for maintainability
/src
/components
Home.js
About.js
...
/routes
AppRouter.js
...

Performance Optimization:

// Optimize route rendering for improved app speed
<Route
path="/dashboard"
component={Dashboard}
exact
/>

Accessibility:

// Ensure your routes are accessible to all users
<Route
path="/dashboard"
component={Dashboard}
aria-label="Dashboard"
/>

Conclusion:

React Router is a powerful library for client-side applications. In this blog, we have covered different techniques with the code example, which will help you in creating navigable and user-friendly applications. React router will help you in both the scenarios i.e., simple websites or complex web apps. It is an essential tool in your React development toolkit.

--

--