SpeedDialAction with react-router-dom Link

Viewed 1030

My SpeedDialAction looks like this:

<SpeedDialAction key="Add" icon={<AddIcon />} tooltipTitle="Add" />

I want to navigate to /add when the action is clicked. Is there a way to do this without using onClick and using the push /add to the history manually?

For example a button allows something like this:

<Button
  component={Link}
  to={`ticket/${ticket.id}`}
  variant="contained"
  color="primary"
>
  Details
</Button>
1 Answers

You can wrap the icon with <Link />.

Based on their example, you can wrap it like this:

const withLink = (to, children) => <Link to={to}>{children}</Link>;

const actions = [
  { icon: withLink("/about", <LiveHelpIcon />), name: "About" },
  { icon: withLink("/users", <GroupIcon />), name: "Users" }
];

(You can obviously also do it in the "normal" way)

{ icon: <Link to="/about"><LiveHelpIcon /></Link>), name: "About" },

Then, wrap the <SpeedDial /> with <Router> and add <Switch> just after it, like this:

<Router>
  <SpeedDial
    ariaLabel="SpeedDial example"
    className={classes.speedDial}
    icon={<SpeedDialIcon />}
    onClose={handleClose}
    onOpen={handleOpen}
    open={open}
  >
    {actions.map(action => (
      <SpeedDialAction
        key={action.name}
        icon={action.icon}
        tooltipTitle={action.name}
        onClick={handleClose}
      />
    ))}
  </SpeedDial>
  <Switch>
    <Route path="/about">
      <div>About</div>
    </Route>
    <Route path="/users">
      <div>Users</div>
    </Route>
    <Route path="/">
      <div>Home</div>
    </Route>
  </Switch>
</Router>

Working example: https://codesandbox.io/s/material-ui-speeddial-react-router-dom-bmmwi

Related