Search code examples
htmlcssreactjsstyled-components

Styling based on attr on Styled components


I am working with details and summary tags in React using styled-components, I want to be able to style the summary tag based on if the details is open or not using the details attribute boolean flag.

<Details open>
  <summary>Epcot Center</summary>
  <p>Epcot is a theme park at Walt Disney World Resort featuring exciting attractions, international pavilions.</p>
</Details>

Please how do I achieve this CSS markup below in styled-components?

details[open] > summary {
color: red
}

I tried this and it did not work, please help

const Details = styled.details`
  [open] > summary {
    color: white;
    background: tomato;
  }
`;

Solution

  • First, you have to render <Details open /> and not <details open />. And, in <Details /> definition:

    const Details = styled.details`
      ${({ open }) => open && css`
        & > summary {
          color: white;
          background: tomato;
      }
    `}`;
    

    P.S.: css is an import from styled-components too:

    import styled, { css } from 'styled-components'