How to combine makeStyle classes from parent and child component?

Viewed 3373

How can I pass makeStyle classes from parent component to child component and combine them with the makeStyle classes in the child component? E.g. as below adding the breakpoint hiding to the child component style.

Example child component:

import React from "react"
import { Button } from "@material-ui/core"
import { makeStyles } from "@material-ui/core/styles"

const useStyles = makeStyles(theme => ({
  button: {
    background: "#000",
    color: "white",
    //lots of other css here so we dont want to repeat it in the parent component

  },
}))

export default function PrimaryButton(props) {
  const classes = useStyles()
  const { children, fullWidth = false } = props

  return (
    <Button
      fullWidth={fullWidth}
      className={classes.button}
      variant="contained"
    >
      {children}
    </Button>
  )
}

Example parent component:


import React from "react"
import { PrimaryButton } from "components/PrimaryButton"
import { makeStyles } from "@material-ui/core/styles"

const useStyles = makeStyles(theme => ({
  primaryButton: {
    display: "inline-block",
    [theme.breakpoints.down("sm")]: {
      display: "none",
    },
  },
}))

export default function PrimaryButton(props) {
  const classes = useStyles()

  return (
    <PrimaryButton
      className={classes.primaryButton}
    >
      Button text
    </PrimaryButton>
  )
}

1 Answers

clsx is used internally within Material-UI and is a convenient utility for combining multiple class names. In your child component, you can grab className from the props and then use className={clsx(className, classes.button)} in the Button it renders:

import React from "react";
import { Button } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";
import clsx from "clsx";

const useStyles = makeStyles(theme => ({
  button: {
    background: "#000",
    color: "white"
  }
}));

export default function PrimaryButton(props) {
  const classes = useStyles();
  const { children, className, fullWidth = false } = props;

  return (
    <Button
      fullWidth={fullWidth}
      className={clsx(className, classes.button)}
      variant="contained"
    >
      {children}
    </Button>
  );
}

Edit combine class names

Related