27

Given these two components:

import Link from '@material-ui/core/Link';
import { Link } from 'react-router-dom';

Is there a way to get the style from Material-UI with the functionality of react-router-dom?

Ninjakannon
  • 3,751
  • 7
  • 53
  • 76
Marcelo Velasquez
  • 585
  • 1
  • 4
  • 12

2 Answers2

65

You can use the component prop of Material-UI's Link to integrate with Link in react-router-dom. You can do the same thing with Material-UI's Button.

Here's an example showing both:

import React from "react";
import { Route } from "react-router";
import { BrowserRouter as Router, Link as RouterLink } from "react-router-dom";
import Link from "@material-ui/core/Link";
import Button from "@material-ui/core/Button";

export default function LinkRouter() {
  return (
    <Router>
      <div>
        <Link component={RouterLink} to="/">
          Link to Home
        </Link>
        <br />
        <Link component={RouterLink} to="/inner">
          Link to inner page
        </Link>
        <br />
        <Button
          variant="contained"
          color="primary"
          component={RouterLink}
          to="/inner"
        >
          Button to inner page
        </Button>
        <Route path="/" exact>
          <div>Here's Home</div>
        </Route>
        <Route path="/inner">
          <div>Here's the inner page</div>
        </Route>
      </div>
    </Router>
  );
}

Edit Use Link with react-router Link

Documentation: https://material-ui.com/guides/composition/#link

Ryan Cogswell
  • 75,046
  • 9
  • 218
  • 198
  • This is wonderful, but for `Button`, it has to be `LinkComponent={RouterLink}` instead of `component={RouterLink}` – Geeky Quentin Apr 12 '23 at 04:45
  • @GeekyQuentin That is not correct. If the `component` prop is specified as [something other than `button`](https://github.com/mui/material-ui/blob/v5.12.0/packages/mui-material/src/ButtonBase/ButtonBase.js#L293) it will be used. It is not necessary to use the `LinkComponent` prop instead (though `LinkComponent` will also work). – Ryan Cogswell Apr 12 '23 at 13:47
7

I have created a wrapper component to merge both Link so it is not necessary to add the component prop every time.

import { LinkProps, Link as MuiLink } from "@mui/material";
import { Link as ReactRouterLink } from "react-router-dom";

import React, { FC } from "react";

const Link: FC<LinkProps> = props => {
  return (
    <MuiLink {...props} component={ReactRouterLink} to={props.href ?? "#"} />
  );
};

export default Link;

And you can use is as you would use the MUI/LINK:

import Link from './components/Link';

<Link href="path_to_link">LINK</Link>
T04435
  • 12,507
  • 5
  • 54
  • 54