How to programmatically navigate to a page using TypeScript and a React Hook

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

In this sample code, we make a div clickable. When clicked, the div uses the react useNavigate hook from the React Router Dom package to load a route named “load” that accepts a lot number URL parameter. You can of course use the Link element’s “to” property to navigate, but in this post I wanted to show navigation using a div and the onClick event.

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, 'LOT101')}>Navigate to Lot Detail</div>      
  );

}

export default Loads;

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