1

I am trying to pass props from NavLink in react-router-dom to another component (component that router routes to). The code is:

       <HashRouter>
                <div className="navigation">
                    <NavLink to="/" className="navigation-link">Home</NavLink>
                    <NavLink quizid="60fcf0f3b55bab18d841e4c3" className="navigation-link" 
                        to={{
                            pathname:'/thisquiz',                        
                            state: "60fcf0f3b55bab18d841e4c3" 
                        }} exact>Quiz</NavLink>
                </div>

                <div>
                    <Route default exact path="/" component={Home}></Route>
                    <Route path="/thisquiz" component={Quiz}></Route>
                </div>
        </HashRouter>

In the Quiz component:

let location = useLocation();
console.log("The state is "+location.state);

The output shows The state is undefined. Please help.

zhulien
  • 5,145
  • 3
  • 22
  • 36
  • in your quiz component, you don't need that `useLocation` hook. Simple do `props.location.state` and you should get your data – AdityaParab Jul 27 '21 at 09:14
  • Passing props in the url worked for me. https://stackoverflow.com/questions/30115324/pass-props-in-link-react-router – Tisa Maharjan Jul 30 '21 at 07:07

1 Answers1

1

Try

<NavLink quizid="60fcf0f3b55bab18d841e4c3" className="navigation-link" 
    to={{
         pathname:'/thisquiz',                        
         id: { id:  "60fcf0f3b55bab18d841e4c3" }
    }} 
    exact
>
    Quiz
</NavLink>

then

const Quiz(props) => {
    
console.log(props.location.id);

     return (
        // code here
     )
}

Also, would be good if you change your div tag on <div className="navigation"> for a <nav> tag.

https://medium.com/@bopaiahmd.mca/how-to-pass-props-using-link-and-navlink-in-react-router-v4-75dc1d9507b4

danihazler
  • 413
  • 1
  • 6
  • 13