0

In react-router v6 the match.params has been removed, with only the useParams() hook available. Now I can't figure out the tweak. The code below is made on Router v4. How can I make the indicated code work using useParams(). Can't figure it out:

import React, { Component } from "react";
import Palette from "./Palette";
import Seeds from "./Seeds";
import { makePalette } from "./ColorHelpers.js";
import { Route, Routes, useParams } from "react-router-dom";

export default class App extends Component {
  findPalette(id) {
    return Seeds.find(function (palette) {
      return palette.id === id;
    });
  }

  routeProps() {
    let id = useParams()
  }

  render() {
    return (
      <Routes>
        <Route exact path="/" element={<h1>PALETTE LIST GOES HERE</h1>} />
        <Route
          exact
          path="/palette/:id"
          render={routeProps => ( // <-- this code
            <Palette
              palette={makePalette(
                this.findPalette(routeProps.match.params.id)
              )}
            />
          )}
        />
      </Routes>
    );
  }
}

I have tried changing the render to element and removing the arrow function routeProps => () into a separate function with useParams().

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Harry 2gks
  • 15
  • 2
  • 1
    I think refactoring to functional component can help here! – RK_oo7 May 22 '23 at 12:01
  • Just FYI, the `props.match` wasn't replaced by the `useParams` hook, `react-router@5` has the `useParams` hook too. What changed is the `Route` component API; route props were removed in `react-rotuer@6`. – Drew Reese May 22 '23 at 16:54

1 Answers1

2

You’re trying to use the useParams hook inside a class component, which won’t work since hooks can’t be used directly in class components. Either refactor your component as a functional component or wrap it in a higher order component as described here:

How can I use React hooks in React classic `class` component?

Once you do so, you can destructure the id parameter returned from the useParams hook:

const {id} = useParams();

Move this destructured assignment out of the routeProps function into the body of the functional component. Then you can access id in your bolded lines with findPalette(id).

ionosphere
  • 373
  • 2
  • 13
  • Thanks a lot! Don't know how I missed the fact that useParams doesn't work inside a class component. this was big help – Harry 2gks May 22 '23 at 13:26