Search code examples
cssreactjsmaterial-uistyled-components

Why does styled() not style the MUI <TextField /> componenet?


I've already found the work around, but I was wondering why this code works:

<TextField
   label='Zip Code'
   size='small'
   InputProps={{
     style: { borderRadius: '.4rem' },
   }}
   sx={{ width: '15rem' }}
  />

But not this code:

const StyledTextField = styled(TextField)({
  borderRadius: '.4rem',
  width: '15rem',
});

<StyledTextField label='Zip Code' size='small' />

In the latter code, borderRadius and width from styled(TextField) didn't apply.


Solution

  • The CSSs from style-component does apply to the TextField. However, the MUI TextField is actually composed by a root div grouping multiple child divs as shown in the bellow snippet. You are attempting to apply border-radius to the root container, which doesn't even have a border. Therefore, the border of the TextField is not changed.

    <div> <!--Root container, with border:0 rule on it.-->
        <div> ... </div> <!--The 'Zip Code' Label-->
        <div> ... </div> <!--Input field container, border is implemented on this.-->
    </div>
    

    However when using InputProps the styles are actually applied to the Input field container, which is where the border you see is actually implemented.

    Because of this, generally you should to use the props MUI exposed to customize the styles, especially since MUI props are highly flexible for customizing CSS.

    Note that sx={{ width: '15rem' }} also applies the width to the root container, so the width set by styled-component does work. If not, there are probably some other CSS interfering, though as mentioned you should use the props exposed by MUI if possible.