JavaScriptJavaScript FrameworksReact

Creating Routes in ReactJS Using React Router Dom 6

In this video, we’ll install React Router Dom 6 and create routes for our app. To learn more about all the new changes and how to upgrade to version 6, please visit https://reactrouterdotcom.fly.dev/docs/en/v6/upgrading/v5

Below are two examples of changes that you will need to adhere to if you’re running version 6.

  • React Router v6 introduces a Routes component that replaces Switch. In order to use v6, you’ll need to convert all your <Switch> elements to <Routes>.
  • React Router v6 introduces an element property that replaces the render property/function. Thus passing URL parameters to class components is a little different. There are no changes to function components.

Install React Router Dom 6

Install the react router dom version 6 using the command terminal. Install without the version number will always pull the latest stable version. At the time of this post, the latest version version is 6. If you want to install the more precise version number, then explicitly append the @ symbol follow by the version number.

npm install react-router-dom

#Or version 6

npm install react-router-dom@6

index.js

Import and wrap the root component with the BrowserRouter.

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

import * as serviceWorker from './serviceWorker';

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

serviceWorker.unregister();

App.js Component

In the App.js module, import Routes and Route from react-router-dom then create route paths to each component. Below is an example of a route to the /flights/:id url.

import React from 'react';
import { Routes, Route} from 'react-router-dom';
import { Nav, Footer, FlighData, FlightList } from "./components";
import './App.css';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { flightData: FlighData };
  }

  render() {
    return (
      <div className="App">
        <Nav />
        <Routes>
          <Route path="/flights/:id" element={ <FlightList flightData={this.state.flightData} />} />
        </Routes>
        <Footer />
      </div>
    );
  }
}
export default App;
Verified by MonsterInsights