Search code examples
reactjsreact-routerreact-props

pass props to new page via react-router Link


I am trying to pass a prop courseid to a new page when I click the link whilst using react-router-dom But I dont seem to be able to access it. I have tried different ways I have found, but none let me access courseid on the new page

In courseListItem I have access to props.course.id I have a button that takes me to '/holes'

<Link
                        to={{
                          pathname: `/holes`, state: {courseid: props.course.id}
                          }} >
                          <button  
                            className="btn btn-primary tooltips float-left" 
                            data-placement="left" 
                            data-toggle="tooltip" 
                            data-original-title="view"
                            ><i 
                            className="fa fa-edit">

                            </i> 
                          </button>
                      </Link>

From what I have read, I can use state: {courseid: props.course.id} to pass courseid to the new page, and then on the new page, use location.state.courseid to access courseid.

Using location.state.courseid on the new page gives me an error unexpected use of location

I found a post saying to use window.location.state.courseid this got rid of the error but when I try and click the button to go to /holes, I get another error Uncaught TypeError: Cannot read properties of undefined (reading 'courseid') so obviously not finding the courseid

Please can someone explain where I am going wrong? Or what is the best way to pass courseid to the new page.

courseid is part of a course object and /holes is a page that has a form on it, but I only need the id so that when I submit the form, it can send the id with the post request to save the holes entered on the form to the correct course.


Solution

  • what type of your component functional component or class component if you write on functional component you can use useLocation hooks from react-router-dom if you using class component you should use location props from your component.

    maybe your component be like this, its just example to access state on location using useLocation

    import { useLocation } from "react-router-dom";
    
    const Holes = () => {
      const location = useLocation();
    
      return (
        <div>
          <h1>HOLES</h1>
          <h2>{location.state.courseid}</h2>
        </div>
      );
    };
    
    export default Holes;