react-router-dom v6 useNavigate passing value to another component

version 6 react-router-dom

I know the question got answered but I feel this might be helpful example for those who want to use functional components and they are in search of passing data between components using react-router-dom v6.

Let’s suppose we have two functional components, first component A, second component B. The component A wants to share data to component B.

usage of hooks: (useLocation,useNavigate)


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

function ComponentA(props) {

  const navigate = useNavigate();

  const toComponentB=()=>{
navigate('/componentB',{state:{id:1,name:'sabaoon'}});
  }

  return (
   <>
<div> <a onClick={()=>{toComponentB()}}>Component B<a/></div>
</>
  );


}


export default ComponentA;

Now we will get the data in Component B.

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

 function ComponentB() {

    const location = useLocation();
   
        return (

            <>
               
<div>{location.state.name}</div>

            </>
        )
    }

export default ComponentB;

Note: you can use HOC if you are using class components as hooks won’t work in class components.

Leave a Comment