How to call a component onClick of a button in a functional component with MaterialUI Button

Viewed 1496

I'm using Material UI for a button and want to render a different functional component onClick of a button. I'm doing this all in a functional component as well. ( is the component I want to trigger)

const driveAction=props =>{
    return <SharedDriveAction/>;
}


const Vehicle = ({vehicle}) => {
const classes = useStyles();

return (
<Button
    onClick= {() => { driveAction }}
    size="small"
    color="secondary"
    className={classes.button}
    >
  Drive
 </Button>
);
}

export default Vehicle;
3 Answers

It looks like you want to leverage some state to conditionally render the button.

If you want to control whether or not the button is visible based on a click action, keep track of which component should render in state, then toggle that state with the onClick handler.

If what I am suspecting is true, then this should do the trick for you.

const Vehicle = ({vehicle}) => {

    const classes = useStyles();

  // Controls whether the drive action is rendered or not
  const [showDriveAction, setShowDriveAction] = React.useState(false)

  return showDriveAction ?
    <SharedDriveAction/> :
    <Button
      onClick= {() => setShowDriveAction(true)}
      size="small"
      color="secondary"
      className={classes.button}
    >
      Drive
    </Button>
}

export default Vehicle;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

You can use conditional render with react state.

and if you want to toggle use Something like that:

const Vehicle = ({ vehicle }) => {

  const classes = useStyles();
  const [showDrive, setShowDrive] = React.useState(false)

  return (
    <div>
     {showDriveAction ?
       <SharedDriveAction/> :
       <Button
         onClick= {() => setShowDriveAction(!showDriveAction)}
         size="small"
         color="secondary"
         className={classes.button}
       >
         Drive
       </Button>}
    </div>
  )
}

More simply speaking, have your overarching component have a state variable of open for the conditional render. OnClick, hook this.setState (for class components) to toggle the open variable. Inline conditional rendering can be handled quite easily in the below example.

{  props.open ? <Component/> : null }
Related