Roy Prins
Roy Prins

Reputation: 3080

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:

Upvotes: 1

Views: 139

Answers (1)

Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36179

  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.

Upvotes: 1

Related Questions