How can I migrate this app from React Router v5 to v6?

Viewed 47

I'm having a lot of troubles trying to migrate this Pokedex app from routing v5 to routing v6, I'm new in React so I can't totally understand the code, I was following this guide: video.

I already tried using the documentation but there's some parts that I don't know how to apply in my code.

Here's the main:

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import {BrowserRouter} from 'react-router-dom'
import {createBrowserHistory} from 'history'


const history = createBrowserHistory();

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <BrowserRouter history ={history}>
    <App />
    </BrowserRouter>
  </React.StrictMode>
)



This is my App.jsx:

import {Route, Routes} from 'react-router-dom'
import React from 'react';
import Pokedex from './Pokedex';
import Pokemon from './Pokemon';


function App() {


  return (


  
      <Routes>
        <Route path="/" element={<Pokedex />} />
        <Route path="/:pokemonId" element={<Pokemon />} />
      </Routes>
    );
  }
  
  export default App;

This is my Pokemon.jsx here's where the problem gets confusing to me, because I don't understand how to change this match.params into Navigate with same or similar params functions:

import React from 'react'

const Pokemon = ({ match }) => {
  const {pokemonId} = match.params;
  return (
    <div>{`this is a pokemon with id ${pokemonId}`}</div>
  );
};

export default Pokemon;

And here's part of the Pokedex.jsx where the problem gets bigger, because history.push problems can only be solved by using withRouter, and that's no longer supported by Router v6:

const Pokedex= props => {

  const {history} = props;
  const classes = useStyles();
  const [pokemonData, setPokemonData] = useState(mockData);


  const getPokemonCard = (pokemonId) => {
    console.log(pokemonData[`${pokemonId}`]);
    const {id, name } = pokemonData[`${pokemonId}`];
    const sprite = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${id}.png`;


    
    return (
    <Grid item xs={4} key={pokemonId}>
      <Card onClick={() => history.push(`/${pokemonId}`)} >

So that's my problem in general, I know navigate is way easier to use and I can understand a bit how to make some routing, but I just can't understand how to migrate this code to it, Hope someone can save me, I will appreciate it a lot.

1 Answers

You should use the useParams() hooks to get your parameters and useNavigate() to replace history:

import {  useParams } from "react-router";
...
const { pokemonId } = useParams();

////

import {  useNavigate } from "react-router";
...
const navigate = useNavigate();
...
navigate(`/${pokemonId}`)
Related