Search code examples
reactjsreact-routerreact-router-v4react-props

How can I pass function using props in React Router Link?


I have to pass a function to another component using Link

    testFavorite=()=>{
        console.log("work")
    }

    <Link 
       to={{
       pathname: '/popular',
         state:{
            testFavorite: this.testFavorite
         }
       }}>
   Popular</Link>

This is how I call a function this.props.location.state.testFavorite();

This is giving me this error

DataCloneError: Failed to execute 'pushState' on 'History': () => testFavorite() could not be cloned.


Solution

  • In <Link /> component, I replace "state" property with "data" property. And it works now!

    <Link 
        to={{
           pathname: '/popular',
           data:{
              testFavorite: this.testFavorite
           }
        }}
    >
       Popular
    </Link>
    

    It will be accessable with this: this.props.history.location.data