Marcelo Velasquez
Marcelo Velasquez

Reputation: 713

Can you use Material-UI Link with react-router-dom Link?

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?

Upvotes: 40

Views: 27492

Answers (2)

T04435
T04435

Reputation: 14022

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>

Upvotes: 14

Ryan Cogswell
Ryan Cogswell

Reputation: 81126

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

Upvotes: 85

Related Questions