Search code examples
cssreactjstypescriptvisual-studio-codestyled-components

Share the same styles between two types of component with React Styled Components


I would like to apply exactly the same styles to a styled input element and a styled select element.

Currently, I'm using string interpolation to do this:

const styles = `
    background-color: white;
    width: 100%;
    border: 0 solid transparent;
    border-radius: 10px;
    margin-bottom: 20px;
    padding-top: 5px;
    padding-bottom: 5px;
    font-size: 1.2rem;
`

const Select = styled.select`${styles}`
const Input = styled.input`${styles}`

Is there a better way of doing this which doesn't involve using a 'raw' string? The disadvantage of using the raw styles string is that Visual Studio Code doesn't syntax-highlight it:

enter image description here


Solution

  • You have few options here:

    css helper function:

    const styles = css`
      background-color: white;
      // ...
    `;
    
    const Select = styled.select`${styles}`;
    const Input = styled.input`${styles}`;
    

    "as" polymorphic prop (added in v4):

    <Select as="input">
      ...
    </Select>
    

    withComponent method (candidate for deprecation):

    const Select = styled.select`
      background-color: white;
      // ...
    `;
    const Input = Select.withComponent('input');