Search code examples
cssreactjsstyled-components

Apply same styling on multiple elements in component


const GreenRow = styled.div`
  background-color: green;
`
const RedRow = styled.div`
  background-color: red;
`
const YellowRow = styled.div`
  background-color: yellow;
`
const GreyRow = styled.div`
  background-color: grey;
`

const MyComponent = () =>
  <div>
    <GreenRow>Green row</GreenRow>
    <div>Blue row</div>
    <RedRow>Red row</RedRow>
    <YellowRow>Yellow row</YellowRow>
    <GreyRow>Grey row</GreyRow>
  </div>

I'm using styled-components to style elements in a component.

I want to apply a repeated styling (e.g. font-weight) on some elements in a component. Some of these component are already styled with styled-component, so this would be some kind of "second dimension" styling.

For example, if I could define styling with a certain classname, I could then apply that classname to each of those elements. But as I've understood, styled-components don't return any classname. And I don't want to start defining styles in other files than the component itself.

Another thought is to render styling with styled-component's css library (see code below) and include it in every applicable styled-component definition. But then I would need to convert some elements to styled-components just for this purpose (as they aren't styled otherwise).

const FontWeight = css`
  font-weight: 600;
`

What would be the most succinct way to apply this "second dimension" styling?


Solution

  • You can interpolate a function into the template literal, which gets passed the props of the component with ${props => props.component_name && css ... }.

    In the following, I hook into Row and add some additional styling for Green:

    import styled, { css } from styled-components
    
    const Row = styled.div`
      /* Generic row styling */
      font-weight: 600;
    
      /* Unique row styling */
      ${props => props.Green && css`
        background: green;
      `}
    
    `
    

    Note that you'll additionally need to import css!

    Now all you have to do is render the row with the additional property when you want a green one:

    render(
      <div>
        <Row>Normal Row</Row>
        <Row Green>Green Row</Row>
      </div>
    );
    

    The green row will inherit all of the styling of the regular rows, and also inherit the rules that are unique to that specific element.

    Hope this helps!