1

I'm trying to create a custom button component using MUI on a React JS project. I've checked the docs and I discovered that I can do this using styled components. All worked well with the code presented below. The problem is that I want to create a more "customizable" component. I have inside my theme file 2 sets of colors (primary and secondary). The fact is that I want to create a button that is able to take a prop for this set of colors (primary / secondary).

import * as React from 'react';
import ButtonUnstyled, {
  buttonUnstyledClasses,
  ButtonUnstyledProps,
} from '@mui/core/ButtonUnstyled';
import { styled } from '@mui/system';
import { theme } from '../../theme';

const CustomButtonRoot = styled('button')(`
  background-color: ${theme.palette[props.type].main};
  padding: 15px 20px;
  border-radius: 10px;
  color: #fff; 
`);

interface TodoButtonProps {
    unstyledProps: ButtonUnstyledProps,
    type?: 'primary' | 'secondary'
}

function CustomButton(props: TodoButtonProps) {
  return <ButtonUnstyled {...props} component={CustomButtonRoot} />;
}

export default CustomButton

The question is: How I can include this prop inside the styled component code?

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230

1 Answers1

4

Pass a callback. In this callback the first argument is the props of the styled component. You can also use the style object instead of template string. More detail in this answer.

const CustomButtonRoot = styled("button")(
  ({ theme, myColor }) => `
  padding: 15px 20px;
  border-radius: 10px;
  color: ${myColor}; 
`
);
<CustomButton myColor="red">abc</CustomButton>

Codesandbox Demo

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
  • It works well, but I have a little problem. I receive this error on my component: Type '{ children: string; btnColor: "secondary"; }' is not assignable to type 'IntrinsicAttributes & TodoButtonProps'. Property 'children' does not exist on type 'IntrinsicAttributes & TodoButtonProps'.ts(2322) – Cătălin Avasiloaie Oct 23 '21 at 07:02
  • @CătălinAvasiloaie see my codesandbox demo. – NearHuscarl Oct 23 '21 at 07:07