Skip to content

Instantly share code, notes, and snippets.

@herr-vogel
Last active November 16, 2021 10:14
Show Gist options
  • Star 40 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save herr-vogel/0b5d4f3c28f08dc6cc4a2fd4f7b4a4df to your computer and use it in GitHub Desktop.
Save herr-vogel/0b5d4f3c28f08dc6cc4a2fd4f7b4a4df to your computer and use it in GitHub Desktop.
Using Material-UI Button with Next.js Link
import React from 'react'
import Link from 'next/link'
import Button from '@material-ui/core/Button'
const ButtonLink = ({ className, href, hrefAs, children, prefetch }) => (
<Link href={href} as={hrefAs} prefetch>
<a className={className}>
{children}
</a>
</Link>
)
// https://material-ui.com/demos/buttons/#third-party-routing-library
const RenderButton = () => <Button component={ButtonLink} href={'/foo'}>bar</Button>
@Guneetgstar
Copy link

Why so much discussion over it? Is there something wrong with this:

import RLink from 'next/link'
import {Link} from "@material-ui/core";

<RLink href={"/privacy"} passHref>
   <Link>
         Privacy Policy
   </Link>
</RLink>

@ats1999
Copy link

ats1999 commented Nov 4, 2020

You don't need to wrap Link with RLink.
RLink is alone enough to handle routing.

@Guneetgstar
Copy link

Guneetgstar commented Nov 4, 2020

@ats1999 Yeah sure I did that for styling the subcomponets as I don't want to write custom css 😉
And another pros for adding link is that Link wraps the children inside <a> tag which is a requirement for me(for better SEO) and that's why you can see passHref prop in RLink tag.
Most importantly the purpose of this whole thread is to use Link with RLink so thats what I did and shared.

@ats1999
Copy link

ats1999 commented Nov 4, 2020

Ohh!

@kachar
Copy link

kachar commented Feb 3, 2021

One more wrapper for both Link and Button components can be found here (typescript version) https://gist.github.com/kachar/028b6994eb6b160e2475c1bb03e33e6a

@EddyVinck
Copy link

I had a ref error for my wrapped Material UI Button in a NextJS Link, which is what I was searching for when I found this thread. I didn't need any of the above, except wrapping my button with React.forwardRef

import { makeStyles } from "@material-ui/core/styles";
import { Button as MuiButton, ButtonProps } from "@material-ui/core";

const useStyles = makeStyles((theme) => ({
  root: {
    // your styles
  },
}));

interface Props extends ButtonProps {}

export const Button: React.FC<Props> = React.forwardRef((props, ref) => {
  const classes = useStyles();

  return <MuiButton ref={ref} className={classes.root} {...props} />;
});
Button.displayName = "Button";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment