Search code examples
reactjsstylesstyled-components

Styled Components / React - Style on Fragment element


I have a question with StyledComponents, it's possible to create a style using a React.Fragment or any other existing component?

I use this example (The intention is the Style ContainerFragment paints the background on blue and use all the styles)

Codepen

If it's not possible, exists another workaround? Explicit using Fragment as an example.


Update: I made a specific question with my real problem on this question


Solution

  • If you need to style a Fragment then you probably shouldn't be using it in the first place. Fragments exists as a workaround to return adjacent JSX elements, they don't render anything to the DOM so they can't be stylized.

    This isn't correct:

    const ContainerFragment = styled(React.Fragment)`
      border: 1px solid red;
      display: flex;
      height: 100vh;
      width: 100vw;
      justify-content: center;
      align-items: center;
      background: blue; 
    `
    

    A Fragment is not like a div. It won't render anything to the DOM, that's the entire point of having it.