How to pass custom arguments to Styled Components using Typescript

How to pass custom arguments to Styled Components using Typescript

React + Styled-components + Typescript

Typescript is a superset of JavaScritpt with a syntax for types that helps you a lot to not commit any errors regarding types or unexisting properties.

ReactJS is super useful to easily and fast create beautiful and responsive frontends.

Styled-components is a React Library that makes styling a React Component super more easy and organized, although it remains customizable.

Typescript + ReactJS + Styled-components = 🤯

I like to organize my React components always in a separet folder for each, with a index.tsx and a style.ts for each of them, like that:

image.png

One useful aspect of Styled-components that sometimes is very necessary, is passing arguments to the style you are creating. For some properties you can do it directly, for example, with a Style that is a button, you can do something like this:

<ExampleStyle color = {'blue'}>Teste</ExampleStyle>

And inside the definition of the Style, on the style.ts, you could access this argument by simply:

export const ExampleStyle = styled.button`
  color: ${props => (props.color)}
`

But if you want to set some custom arguments, you can't do it directly, because it is not acceptable without the typing. So, for example, if you want to set the 'visibility' css property, you cannot pass it like that:

<ExampleStyle color = {'blue'} visibility = {'visible'}>Teste</ExampleStyle>

You need to firstly define the props to the Style, inside of it's definition, by creating a interface:

interface props {
  visibility: string;
}

And then you say your style receives this interface by addind:

export const ExampleStyle = styled.button<props>`
  color: ${props => (props.color)};
  visibility: ${props => (props.visibility)};
`

And that's it!