Create a route that uses and accepts a parameter using React Router

Post author: Adam VanBuskirk
Adam VanBuskirk
7/3/23 in
Tech
ReactTypeScript

This example creates a route that navigates to the <Load /> component while passing in a parameter named “lot”. The Load component then uses the useParams hook from the React Router Dom package to access the passed in parameter. To keep the example brief, I omit much code, but you will find below the key points, such as the route definition, the component that uses the parameter, and the onClick that passes it.

The Route, Including the URL Parameter

For brevity, the entire App.tsx component is not shown here, but the below line is in that component.

<Route path='load/:lot' element={<Load />} />

The Component

import { useParams } from 'react-router-dom'

function Load() {

    const { lot } = useParams();

    return (
      <div className="mt-2 ms-4 me-4"> 
        You are on the screen for lot # {lot}
      </div>
    );
}

export default Load;

The onClick That Passes The Parameter

Below we have a clickable <div> element and the handler that handles the click, which includes passing the lot number to the /load route.

import { useNavigate } from 'react-router-dom';

function Loads() {

  const navigate = useNavigate();

  const showDetail = (e: React.MouseEvent<HTMLDivElement>, lot: string) => {
    e.preventDefault();
    navigate(`/load/${lot}`)
  } 

  return (
    <div onClick={(e) => showDetail(e, l.number)}>Load Lot Detail</div>
  );

}

export default loads;

The Result

Below is after I click the div. You can see it loaded and read the lot parameter.

Sign up today for our weekly newsletter about AI, SEO, and Entrepreneurship

Leave a Reply

Your email address will not be published. Required fields are marked *


Read Next




© 2024 Menyu LLC