React.js Routing

Introduction to React Router and how to set up routes in your React.js application:

Installation:

Install React Router using npm or yarn:

                                      
                                      npm install react-router-dom
                                      
                                    

Or

                                      
                                      yarn add react-router-dom
                                      
                                    

Setting up routes:

In your application, you set up routes within the main component (often called App.js).

You'll import BrowserRouter as Router, Route, and Switch from react-router-dom.

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

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

export default App;

                                      
                                    

Navigation between routes:

Use the <Link> component provided by React Router to create navigation links between routes without full page reloads.

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

function Navigation() {
  return (
    <nav>
      <ul>
        <li>Home</Link></li>
        <li>About</Link></li>
        <li>Contact</Link></li>
      </ul>
    </nav>
  );
}

export default Navigation;

                                      
                                    

Then, you can use the <Navigation> component wherever you need navigation links in your application.