Search code examples
react-routerbrowser-history

Passing button id in history.push() in React


I two buttons as pictured below. I am navigating users to the registration page using history.push using this code. I want to pass some sort of data to the Registration page like if the user is a "volunteer" or "good cause" based on the button click. I know that it is relatively simple but I cannot figure it out. Thanks.

enter image description here

let history = useHistory();
  const handleClickRegistration = () => {
    history.push({
      pathname: '/Registration',
    });
  };

This is where I am calling the function

          type="submit"
          variant="contained"
          id="volunteer"
          className={classes.button}
          style={{margin: 8}}
          onClick={handleClickRegistration}
        >
      Register as a Volunteer
    </Button>

Solution

  • if you are using the same function on both buttons then use it like

    <Button onClick={()=> handleClickRegistration("volunteer")} >Register as a 
    Volunteer</Button>
    
    <Button onClick={()=> handleClickRegistration("good_cause")} >Register as a 
    Good Cause</Button>
    

    and in handleClickRegistration function send a state in history.push method

    const handleClickRegistration = (userType) => {
    history.push({
      pathname: '/Registration',
      state: { userType: userType }
    });
    };
    

    which you can get in Registration rotue