Search code examples
styled-componentsgrommet

Specify props of a component imported from a UI library in styled-componennts


I am using grommet and styled-components. I have a few places where I use a component provided by grommet and set some similar props. I want to create a styled-components by using that component exported by grommet and specify the set props using styled-components.

Is this possible using styled-components? Below is what I am trying o use.

import { Header } from 'grommet'
import styled from 'styled-components'

const AppHeader = styled(Header)`
    background="brand"
    height="80px"
    pad="small"
`
export default AppHeader

The background, height and the pad are not set on the AppHeader. I only see actual CSS props being set in the examples. So, I wanted to ask if the above is possible?


Solution

  • Yes. It is definitely possible to use styled-components with grommet components.

    In your example, the syntax you provided to styled-components wouldn't work, so following the recommended syntax structure should do the trick as follows:

    const AppHeader = styled(Header)`
      background: #000;
      height: 80px;
      padding: 30px;
    `;
    

    I also noticed you are trying to use grommet's props, such as pad, that would not work with styled-components since it accepts CSS and not grommet props, the simple way, in this case, is just to use padding and that should work.

    Regarding the brand color you are trying to reference, brand isn't defined with CSS colors, so again that wouldn't work. If you'd like to use the brand color, you can always reference the theme color when defining your styled components as follows:

    const AppHeader = styled(Header)`
      background: ${({ theme }) => theme.global.colors.brand};
      height: 80px;
      padding: 30px;
    `;
    

    Here is a full (working) code example:

    import React from "react";
    import { render } from "react-dom";
    import styled from "styled-components";
    
    import { grommet, Header, Heading, Grommet, Paragraph } from "grommet";
    
    const AppHeader = styled(Header)`
      background: ${({ theme }) => theme.global.colors.brand};
      height: 80px;
      padding: 30px;
    `;
    
    const App = () => (
      <Grommet theme={grommet}>
        <AppHeader pad="small">
          <Heading level={3}>
            <strong>Hello World</strong>
          </Heading>
          <Paragraph>Hello from a Grommet page!</Paragraph>
        </AppHeader>
      </Grommet>
    );
    
    render(<App />, document.getElementById("root"));
    
    

    enter image description here