Search code examples
reactjsmaterial-uistyled-components

Better way to use material-system with styled-components


I am trying to use the stack above to customize Material components with the props provided by the Material system (joining with styled-components). The component that I'm testing:

import React from 'react'
import Grid from '@material-ui/core/Grid'

import { spacing, sizing, color, flexbox, display } from '@material-ui/system'
import styled from 'styled-components'

const Row = styled(props => <Grid container {...props} />)`
  ${spacing}
`

export default Row

Everything on screen works very well, but an error on console appear every time that I use a material-system prop. Ex.:

<Row maxWidth='200px'>...</Row>

the following error appear on console:

Warning: React does not recognize the maxWidth prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase maxwidth instead. If you accidentally passed it from a parent component, remove it from the DOM element.

I know that the ...props is passing maxWidth to Grid component (and it's a html element), but I'm confusing about how to use it without these console log's


Solution

  • Let's separate exactly which props are used for styling and which props are sent to the Grid component. Using rest, we can "pull out" certain properties from the props object and send the rest to the Grid component. Then, the properties that we pull out will form the CSS.

    import React from 'react'
    import Grid from '@material-ui/core/Grid'
    
    import { spacing, sizing, color, flexbox, display } from '@material-ui/system'
    import styled from 'styled-components'
    
    
    const Row = styled(
      ({ maxWidth, somethingElse, ...rest }) => <Grid container {...rest} />
    )`
      ${spacing}
      maxWidth: ${props => props.maxWidth || defaultValue1};
      somethingElse: ${props => props.somethingElse || defaultValue2};
    `;
    
    export default Row