Creating Routes in ReactJS Using React Router Dom 5
December 11, 2021
In this video, we’ll install React Router Dom 5 and create routes for our app.
Install React Router Dom 5
Install the react router dom version 5 using the command terminal.
npm install react-router-dom@5
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 Switch 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 { Switch, 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"> <FlightList flightData={this.state.flightData} /> </Route> </Routes> <Footer /> </div> ); } } export default App;