#10 React Router

React Router is a powerful library that allows you to handle routing in a React application. It enables you to navigate between different components, manage URL parameters, and implement nested routes efficiently. In this article, we will cover the basics of React Router, how to set it up, and some advanced routing techniques such as nested routes and handling URL parameters and query strings.

Introduction to React Router

React Router is used to create single-page applications with navigation that mimics multi-page applications. It allows you to:

  • Define multiple routes for different components.
  • Navigate between components without a full page reload.
  • Pass parameters and query strings through URLs.
  • Manage complex routing structures with nested routes.

Setting Up React Router

To get started with React Router, you need to install the library using npm or yarn.

npm install react-router-dom

After installation, you can set up React Router in your application.

Example:

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';

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

ReactDOM.render(<App />, document.getElementById('root'));

In this example, BrowserRouter is used to wrap the application, and Route components define the paths for different components.

Basic Routing

Basic routing involves defining paths and the components that should be rendered when those paths are accessed.

Example:

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

function Home() {
  return <h2>Home</h2>;
}

function About() {
  return <h2>About</h2>;
}

function Contact() {
  return <h2>Contact</h2>;
}

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 exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />
      </div>
    </Router>
  );
}

export default App;

In this example, Link components are used to navigate between different routes without reloading the page.

Nested Routes

Nested routes allow you to define routes within routes, enabling complex and hierarchical routing structures.

Example:

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

function Home() {
  return <h2>Home</h2>;
}

function About() {
  return <h2>About</h2>;
}

function Topics() {
  let { path, url } = useRouteMatch();

  return (
    <div>
      <h2>Topics</h2>
      <ul>
        <li>
          <Link to={`${url}/rendering`}>Rendering with React</Link>
        </li>
        <li>
          <Link to={`${url}/components`}>Components</Link>
        </li>
        <li>
          <Link to={`${url}/props-v-state`}>Props v. State</Link>
        </li>
      </ul>

      <Route exact path={path}>
        <h3>Please select a topic.</h3>
      </Route>
      <Route path={`${path}/:topicId`}>
        <Topic />
      </Route>
    </div>
  );
}

function Topic() {
  let { topicId } = useParams();
  return <h3>Requested topic ID: {topicId}</h3>;
}

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

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

export default App;

In this example, the Topics component defines nested routes for different topics.

URL Parameters and Query Strings

React Router allows you to access URL parameters and query strings to create dynamic routes.

Example with URL Parameters:

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

function Home() {
  return <h2>Home</h2>;
}

function About() {
  return <h2>About</h2>;
}

function User() {
  let { id } = useParams();
  return <h2>User ID: {id}</h2>;
}

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

        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/user/:id" component={User} />
      </div>
    </Router>
  );
}

export default App;

In this example, the User component accesses the URL parameter id using the useParams hook.

Example with Query Strings:

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

function useQuery() {
  return new URLSearchParams(useLocation().search);
}

function Home() {
  return <h2>Home</h2>;
}

function About() {
  return <h2>About</h2>;
}

function Search() {
  let query = useQuery();
  return <h2>Query: {query.get('query')}</h2>;
}

function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/search?query=react">Search React</Link>
            </li>
          </ul>
        </nav>

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

export default App;

In this example, the Search component accesses the query string parameter query using a custom useQuery hook.

Conclusion

React Router is a versatile library for handling routing in React applications. It allows you to create complex and dynamic navigation structures with ease. By understanding the basics of routing, setting up nested routes, and working with URL parameters and query strings, you can build robust single-page applications that provide a seamless user experience.

Stay tuned for more in-depth React tutorials!


Tags

#React #JavaScript #FrontendDevelopment #WebDevelopment #ReactRouter #Routing #SinglePageApplication #NestedRoutes #URLParameters #QueryStrings #ReactTutorial #Programming #Coding #SoftwareDevelopment #UIDevelopment #JSX

Leave a Reply