How to Put Routerlink in IconButton in ReactJS

Viewed 7518

How can i put the routerlink in reactjs button?

I tried these two below: the first one changes the color while the second one, i don't like it since it is reloading the page.

FIRST

<Link to="/settings">
    <IconButton color="inherit">
        <SettingsIcon />
    </IconButton>
</Link>

SECOND

<IconButton color="inherit" href="/settings">
    <SettingsIcon />
 </IconButton>
3 Answers

@BeHappy's solution is good, but you can implement this using composition. No need to use hook.

import React from 'react';
import { Link } from 'react-router-dom';
import { IconButton } from '@material-ui/core';
import SettingsIcon from '@material-ui/icons/Settings';

export default function Component() {
  return (
    <IconButton component={Link} to="/setting">
      <SettingsIcon />
    </IconButton>
  );
}
import React from "react";
import { useHistory } from "react-router-dom";

export default function Component() {
    const history = useHistory();

    return (
        <IconButton color="inherit" onClick={() => history.push("/setting")}>
            <SettingsIcon />
        </IconButton>
    );
}

I was able to inject a Link into IconButton as follows. This approach preserves material-ui classes and CSS styling by capturing them in a span that wraps the Link component. The same span is also used to store the forward reference ref. I'm not sure why exactly it is needed but leaving it out seemed to be generate warnings.

import React from "react";
import { IconButton } from '@material-ui/core';
import SettingsIcon from '@material-ui/icons/Settings';

export default function Component() {
  return (
    <IconButton component={React.forwardRef(
      ({children, ...props}, ref) => (
        <span {...props} ref={ref}><Link>{children}</Link></span>
      )
    )}>
      <SettingsIcon />
    </IconButton>
  )
}
Related