0

I'm populating a grid with various controls (in this example: up-down counter and a text box).

Currently, I'm injecting styles in the cls member (in this example can be e.g. wide-input and narrow-input):

render(): ReactNode {
    const input: CellItem[] = [
        { isUpdown: false, cls: 'wide-input' },
        { isUpdown: true, cls: 'narrow-input' },
    ];

    return (
        <GridContainer>
            input.map(content, index): ReactNode => {
                return (
                    content.isUpdown ?
                        <StyledUpdownCell className={content.cls} /> :
                        <StyledTextBoxCell className={content.cls} /> :
                )               
            }
        </GridContainer>
    );
}

My question is what is the proper way to do it using styled-components?

Is there a way to inject any arbitrary style (content.cls in this example, but tomorrow it could be also setting custom border color for instance)

Tar
  • 8,529
  • 9
  • 56
  • 127

1 Answers1

0

Using styled components, you can have access to props passed to your custom styled component.

So, you could create different 'themes' props which you pass to your StyledUpdownCell and then access those inside the component styles. For example

const StyledUpdownCell = styled.div`
   border-color: ${props => props.warningTheme ? 'red' : 'black'};
`

in use:

<StyledUpdownCell warningTheme />

You could also pass props directly but with a default e.g.

const StyledUpdownCell = styled.div`
   border-color: ${props => props.borderColor || 'black'};
`

in use:

<StyledUpdownCell borderColor="violet" />

It's really up to you and how you want to design your component's API.

Side note: I've found this little library helpful for when creating components which have a lot of different props: https://github.com/yldio/styled-is

nicholascm
  • 621
  • 4
  • 7
  • I want to avoid adding new `prop` for each item I inject. Today it is `max-width: 130px`, tomorrow it can be `border: 1px solid blue;`. I'm trying to find a way to inject any style, without altering the component. – Tar Oct 17 '19 at 14:19
  • Hmm...using a theme you could branch and apply multiple lines of different css per theme as well as having overrides for specific props if you wanted, but that still isn't entirely arbitrary styling. – nicholascm Oct 17 '19 at 14:33