I recently created a style guide with GatsbyJS and needed to provide blocks of CSS as examples. I wanted the blocks to have syntax highlighting, be easy to read and have a quick copy function for those using the guide. I couldn’t find a component that had all the features I needed, so I decedent to make my own with Styled Components.

The finished component can be found in this Gist: https://gist.github.com/tomanagle/4c2ffaa2b2aeffc020f7fa7eb7ba6fa7

The component is going to take a string of CSS, split it, loop through it and add styled wrappers to each segment.

There are four segments to a line of CSS, the rule (width, font-size, margin, ect…), the full colon divider (:), the value and the terminator (;).

The first step is to check to see if the render props is a type of string, we can do that with the following function.

The next step is the split and map function.

Each of the four segments should be individually wrapped and styled. This is where I used styled-components, but you can use any styling module you like.

The map function outputs each of the segments wrapped in their components, followed by a break tag.

The copy button created a text area, puts the render props value in the text area, selects the value of the text area, copies the value and removes the text area from the DOM.

I also created a Styled Component for the copy button.

For safety, I wrapped the output function in a try-catch so I could output a proper error to the user if they use the component wrong, or I can adjust the component for different use cases.

When it’s complete the whole component will look like this:

To use the component, wrap your CSS in your new CSS component.