ReactJS Routing

react

Routing is the process of navigating between different parts of a web application or website. In a single-page application (SPA), routing is used to manage the different views or pages that are displayed to the user.

React Router is a popular library for routing in React applications. It allows you to define the different routes in your application and specify the components that should be rendered for each route.

To use React Router in your application, you will need to install it first:

npm install react-router-dom

Then, you can define your routes in a Router component, which should be the root component of your application. For example:

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

class App extends React.Component {
    render() {
        return (
            <Router>
                <Route exact path="/" component={Home}/>
                <Route path="/about" component={About}/>
                <Route path="/contact" component={Contact}/>
            </Router>
        );
    }
}

In this example, the Router component has three routes defined: one for the root path (/), one for the /about path, and one for the /contact path. Each route specifies a component that should be rendered when the corresponding path is visited.

You can use the Link component from React Router to create links between the different routes in your application. For example:

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

class Navigation extends React.Component {
    render() {
        return (
            <nav>
                <ul>
                    <li>
                        <Link to="/">Home</Link>
                    </li>
                    <li>
                        <Link to="/about">About</Link>
                    </li>
                    <li>
                        <Link to="/contact">Contact</Link>
                    </li>
                </ul>
            </nav>
        );
    }
}