The update for React (v6) and creating routes

Jessica Sewell
2 min readDec 3, 2021

--

For those of you who don’t know I am in a coding bootcamp. We create projects towards the end of a phase to showcase what we have learned throughout that said phase. Recently, we were coming towards the end of a phase and we had to create a project. Some of the requirements were that we use React for the frontend and Ruby on Rails for the backend. To our surprise, we didn’t know React would have their grand update and made changes to how you create routes.

So, if you were a little blindsided by the recent updates of React, I am here to help!

Starting off if you are justing creating a React app, use this command to get started:

npx create-react-app demo-projectcd demo-project

If you go to your package.json file and don’t see react-router-dom then install it by using:

npm install react-router-dom 

Now let’s create a component and do some comparisons. In v5 you would create a component using routes like this:

import {BrowserRouter as Router, Route, Switch} from 'react-router-dom'
import React from 'react'
import Home from './Home'
class App extends React.Component {render(){
return (
<Router>
<div className="App">
<Switch>
<Route exact path='/' component={Home}/>
</Switch>
</div>
</Router>
)
}
}
export default App

In v6, the way to write a path has changed and some changes to syntax as well. Here is a route in v6:

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'
import React from 'react'
import Home from './Home'
function App() {return (
<Router>
<Routes>
<Route index path="/" element={<Home/>}/>
</Routes>
</Router>
)
}

Some things to point out is that Switch has been dropped for Routes. Instead of exact path, it is now index path and component is now element. Also there are syntax changes to note in Route, the element should be inclosed in {} and the component itself should be like this <Home/>.

Can’t say much about the update just yet but I’m sure I’ll have more information on what I think about it later. I hope this helped and as always happy coding!

--

--

Jessica Sewell
Jessica Sewell

Written by Jessica Sewell

A software engineering student at Flatiron School.

No responses yet