Search code examples
reactjsstyled-components

Styled components for colored tags


Styled components looks great, but I am having trouble organizing my components. My first venture with is a tag list, that automatically colors the tags. After some trial I came up with a component that can be used like this:

// An array of tags. The string hashes determine the color
<ColorTags tags={post.frontmatter.tags} inline/>

It is implemented as follows:

components/
    ColorTags      // functional component
    ColorTagLI    // styled component
    ColorTagUL   // styled component

With:

// ColorTags
import ColorTagLI from './ColorTagLI'
import ColorTagUL from './ColorTagUL'

export default ({tags, inline}) => 
    <ColorTagUL>
        {tags.map( tag =>
            <ColorTagLI key={tag} colorString={tag} inline>
                <Link to="/">
                    {tag}
                </Link>
            </ColorTagLI>
        )}
    </ColorTagUL>



// ColorTagUL
export default styled.ul`
    list-style-type: none;
    margin: 0;
    padding: 0;
`


// ColorTagLI
const colorHash = new ColorHash({lightness: [0.4, 0.5, 0.6]});

const hslColor = cString => {
    const [h, s, l] = colorHash.hsl(cString)
    return `hsl(${h}, ${s*100}%, ${l*100}%)`
}

export default styled.li`
    color: white;
    background-color: ${props => hslColor(props.colorString)};
    display: ${props => props.inline ? 'inline-block' : 'block'};
    padding: 0.25rem 0.5rem;
    margin: 0.25rem;
    > a { text-decoration: none; color: white; }
`

Some questions I have:

  • What's a good way to discern between styled and regular components? I decided on appending the HTML tag to the styled components, since they are always tied to that.
  • Is it not a problem to have the Link tag inside a Styled component?
  • Should the ColorTag components be in a folder of themselves? Because they are tightly coupled.
  • Is using theinline prop a smart way to switch between configurations? It may result in a lot of conditional statements for margins, padding and media queries... Perhaps better make two different components?

Solution

    1. You can use utility function isStyledComponent.
    2. Why would it be a problem to have a Link component inside styled component?
    3. Matter of opinion, if you believe they are tightly coupled you can create /ColorTag directory with index.js file that exports only what should be exposed.
    4. Yes it may result in a lot of conditional statements, that's why you can extend styles on styled components.

    I hope I understood you right and my answers are clear.