React Routers Tutorial

Learn React Routers with this tutorial. We will teach you the basics of React Routers with examples here. So, that you can understand the fundamentals of Routing in React.

What is React Router?

  1. React Router is a routing library for React applications.
  2. It allows you to navigate between different views in your application without having to reload the page.
  3. React Router works by creating a history stack of the pages that the user has visited.
  4. When the user clicks on a link or enters a URL in the address bar, React Router updates the history stack and renders the corresponding view.
  5. Let's start by setting up React Router in your project.
npm install react-router-dom

Basic Routing Setup

  1. To set up routing in your React application, wrap your components with <BrowserRouter>.
  2. Define routes using the <Route> component.
import { BrowserRouter as Router, Route } from 'react-router-dom';

function App() {
    return (
    <Router>
        <Route path="/" exact component={Home} />
        <Route path="/about" component={About} />
        </Router>
    );
}
    

Route Parameters

  1. You can define route parameters to capture dynamic parts of the URL.
  2. Access these parameters using the props.match object.
<Route path="/user/:id" component={UserDetail} />

// Inside UserDetail component
const userId = this.props.match.params.id;
    

Navigation with Link

  1. Use the <Link> component to navigate between different routes.
  2. It ensures that your app remains a single-page application.
import { Link } from 'react-router-dom';

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

Redirects and Not Found Pages

  1. Use <Redirect> to redirect users to a specific route.
  2. Create a "Not Found" page to handle routes that don't exist.
<Route path="/old-route">
    <Redirect to="/new-route" />
</Route>
<Route path="*" component={NotFound} />
  

Programmatic Navigation

  1. You can also navigate programmatically by using the history object.
  2. Access it using the useHistory hook or via this.props.history in class components.
import { useHistory } from 'react-router-dom';

const MyComponent = () => {
    const history = useHistory();
    history.push('/new-route');
}
    

Route Guards

  1. Implement route guards by rendering or not rendering components based on conditions.
  2. For example, protect routes by checking if the user is authenticated.
<Route path="/admin" render={() => isAuthenticated ? <AdminPanel /> : <Redirect to="/login" />} />

Route Animations

  1. You can add route transition animations with CSS or libraries like React Transition Group.
  2. Animate the mounting and unmounting of route components.
import { CSSTransition } from 'react-transition-group';

<CSSTransition in={match != null} timeout={300} classNames="fade" unmountOnExit>
    <Component />
</CSSTransition>
    

Complete Example

  1. Create a new React app using Create React App or your preferred setup.
  2. npx create-react-app react-router-example
    cd react-router-example
    
  3. Install React Router Dom.
  4. npm install react-router-dom
    
  5. Create the component files for Home.js and About.js in the src folder:
  6. src/Home.js
    import React from 'react';
    
    const Home = () => {
        return (
        <div>
            <h2>Home Page</h2>
            <p>Welcome to the Home page!</p>
        <</div>
        );
    };
    
    export default Home;
        
    src/About.js
    import React from 'react';
    
    const About = () => {
        return (
        <div>
            <h2>About Page</h2>
            <p>Learn more about us on the About page.</p>
        </div>
        );
    };
    
    export default About;
        
  7. Create the main application component (App.js) with routing.
  8. src/App.js
    import React from 'react';
    import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';
    import Home from './Home';
    import About from './About';
    
    function App() {
        return (
      <Router>
            <div>
            <nav>
            <ul>
            <li>
            <Link to="/">Home</Link>
            </li>
            <li>
            <Link to="/about">About
            </li>
            </ul>
            </nav>
    
            <Switch>
                
                
                </Switch>
                </div>
                </Router>
        );
    }
    
    export default App;
            
  9. When you start this application you will notice the changes in your browser.