skip to Main Content

I have a styled component that looks like this:

export const TestClassButton = styled(Button)({ ... })

And I use it like this:

<Tooltip arrow title={"status"}>
   <TestClassButton
     id={"button-status-dialog"}
     onClick={() => setShowDialog(!showDialog)}
   >
     <ListAltIcon />
   </TestClassButton>
 </Tooltip>

Result:

enter image description here

If I try to style a little bit more my styled component like this:

export const TestClassButton = styled((props) => (
  <Button variant={"outlined"} {...props} />
))({ ... });

Then the component where I use it says this:

enter image description here

And the Tooltip stops working. Any idea why is this happening? Isn’t this the propper way to use styled components?

2

Answers


  1. Chosen as BEST ANSWER

    My soultion to avoid extra typos and errors was to separate the Material UI properties from the styled component like this:

    const StyledButton = ({ children, ...props }) => (
       <Button size={"small"} variant={"contained"} {...props}>
          {children}
       </Button>
    );
    
    export const TestClassButton = styled(StyledButton)({ ... });
    

  2. Heh, just posted that it is unobvious on mui page (how to extend components with styled)

    const TestClassButton = styled(Button, { 
      shouldForwardProp: (props) => 
        ['myCustomProp'].every(key => key !== prop),
    })<ButtonProps & { myCustomProp?: boolean  }>(({ theme, myCustomProp }) => theme.unstable_sx({
       background: myCustomProp ? 'red' : 'green',
    }))
    
    const Component = () => {
       return <TestClassButton myCustomProp>TEST</TestClassButton>
    }
    

    you can also do that like this:

    const TestClassButton = styled(Button, { 
      shouldForwardProp: (props) => 
        ['myCustomProp'].every(key => key !== prop),
    })<ButtonProps & { myCustomProp?: boolean  }>(({ theme, myCustomProp }) => ({ 
     variant: 'outlined',
     style: theme.unstable_sx({
       background: myCustomProp ? 'red' : 'green',
      }),
    })
    
    const Component = () => {
       return <TestClassButton myCustomProp>TEST</TestClassButton>
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search