ReactJS - BrowserRouter: A Beginner's Guide to Routing in React

Hello there, aspiring React developers! Today, we're going to embark on an exciting journey into the world of routing in React applications. Don't worry if you're new to programming; I'll be your friendly guide, explaining everything step by step. So, grab a cup of coffee, and let's dive in!

ReactJS - BrowserRouter

Router Concepts

What is Routing?

Imagine you're in a big library. You want to find a specific book, but you don't know where it is. That's where the library catalog comes in handy. It tells you exactly which shelf to look on. In web applications, routing works similarly. It's like a map that tells your app which component to display based on the URL.

Why Do We Need Routing?

Let's say you're building a personal website with different pages: Home, About, and Contact. Without routing, you'd have to manually show and hide components based on user actions. That's tedious and error-prone. Routing automates this process, making your app more organized and user-friendly.

Enter BrowserRouter

In the React world, we have a fantastic tool called BrowserRouter. It's part of the react-router-dom library and helps us implement routing in our React applications. Think of it as your app's personal librarian, always ready to guide users to the right "book" (or in our case, component).

How to Apply Routers

Now that we understand the concept, let's get our hands dirty with some code!

Step 1: Installation

First things first, we need to install the react-router-dom package. Open your terminal and run:

npm install react-router-dom

Step 2: Setting Up BrowserRouter

Let's start by wrapping our main App component with BrowserRouter. Here's how:

import React from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';

const Root = () => (
  <Router>
    <App />
  </Router>
);

export default Root;

In this example, we're importing BrowserRouter and renaming it to Router for simplicity. We then wrap our App component with Router. This sets up the routing context for our entire application.

Step 3: Defining Routes

Now, let's define some routes in our App component:

import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';

const App = () => (
  <div>
    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/contact" component={Contact} />
    </Switch>
  </div>
);

export default App;

Let's break this down:

  • We import Route and Switch from react-router-dom.
  • Switch ensures that only one route is rendered at a time.
  • Each Route component defines a mapping between a URL path and a React component.
  • The exact prop on the home route ensures it only matches the exact path "/".

Step 4: Creating Navigation

Now, let's add some navigation to our app:

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

const Navigation = () => (
  <nav>
    <ul>
      <li><Link to="/">Home</Link></li>
      <li><Link to="/about">About</Link></li>
      <li><Link to="/contact">Contact</Link></li>
    </ul>
  </nav>
);

export default Navigation;

Here, we're using the Link component from react-router-dom. It's like an <a> tag, but it prevents the page from reloading when navigating.

Step 5: Putting It All Together

Let's update our App component to include the navigation:

import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Navigation from './components/Navigation';
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';

const App = () => (
  <div>
    <Navigation />
    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/contact" component={Contact} />
    </Switch>
  </div>
);

export default App;

And there you have it! A basic React application with routing set up.

Advanced Routing Techniques

Now that we've covered the basics, let's look at some more advanced techniques:

1. URL Parameters

Sometimes, you want to pass data through the URL. For example, a user profile page:

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

In your UserProfile component, you can access the id parameter like this:

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

const UserProfile = () => {
  let { id } = useParams();
  return <h1>User Profile for user {id}</h1>;
};

2. Nested Routes

You can nest routes within components. This is useful for complex layouts:

const App = () => (
  <div>
    <Navigation />
    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/users" component={Users} />
    </Switch>
  </div>
);

const Users = () => (
  <div>
    <h1>Users</h1>
    <Switch>
      <Route exact path="/users" component={UserList} />
      <Route path="/users/:id" component={UserProfile} />
    </Switch>
  </div>
);

3. Programmatic Navigation

Sometimes you want to navigate programmatically, like after a form submission:

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

const LoginForm = () => {
  let history = useHistory();

  const handleSubmit = () => {
    // ... handle login logic
    history.push('/dashboard');
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* form fields */}
    </form>
  );
};

Routing Methods Table

Here's a handy table summarizing the main routing methods we've discussed:

Method Purpose Example
<BrowserRouter> Wraps the app to enable routing <BrowserRouter><App /></BrowserRouter>
<Route> Defines a route <Route path="/about" component={About} />
<Switch> Ensures only one route renders <Switch><Route ... /><Route ... /></Switch>
<Link> Creates a link to a route <Link to="/about">About</Link>
useParams() Accesses URL parameters let { id } = useParams();
useHistory() Programmatic navigation history.push('/dashboard');

And there you have it, folks! We've journeyed through the basics of routing in React using BrowserRouter. Remember, practice makes perfect, so don't be afraid to experiment with these concepts in your own projects.

Happy coding, and may your routes always lead you to the right component!

Credits: Image by storyset