Search code examples
reactjstypescriptreact-routerreact-hookstsx

How to pass variable id with history.push()


I am using react-router library to navigate, and history.push() to navigate onClick. When user clicks on a row they will be navigated to 'otherPage'. In 'otherPage' I want to use the variable 'id'. How do I pass this variable?

function handleRowClick(id: number): void {
    // navigates user to another page
    history.push('/otherPage');
}

Solution

  • history.push(route, state);
    

    The optional state param is an object with your custom routing params.

    the state object is available here inside of your component (if not you can wrap it with withRouter hoc)

    this.props.location.state 
    

    Class Component

    Hight Order Component

    import { withRouter } from 'react-router';
    /* other dependencies */
    
    class YourClassComponent {
      render() {
        const { location } = this.props;
        console.log(location.state);
    
        return (
          /* some jsx here */ 
        );
      }
    }
    
    export default withRouter(YourClassComponent);
    

    Functional Component

    Hight Order Component

    import { withRouter } from 'react-router';
    /* other dependencies */
    
    const YourFunctionalComponent = ({ location }) => {
      console.log(location.state);
    
      return (
        /* some jsx here */ 
      );
    };
    
    export withRouter(YourFunctionalComponent);
    

    React hook

    import { useLocation } from 'react-router-dom';
    /* other dependencies */
    
    const YourFunctionalComponent = ({ location } ) => {
      const location = useLocation();
      console.log(location.state);
    
      return (
        /* some jsx here */ 
      );
    };