10

I looking into styled-components and trying the examples from the website but I also wanted to use TypeScript.

I have this simple example here

import React from 'react'; import './App.css'; import styled from 'styled-components'; interface IProps{ primary: boolean } const App:React.FC<IProps> = ({primary}) => { return ( <div className="App"> <h1>Styled Components</h1> <Button>Normal</Button> <Button primary>Primary</Button> </div> ); } const Button = styled.button` background: ${props => props.primary ? 'red' : 'white'}; color: ${props => props.primary ? 'white' : 'red'}; font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 1px solid green; border-radius: 3px; ` export default App; 

but I'm getting errors on the primary prop

I getting the error

Property 'primary' does not exist on type 'ThemedStyledProps<Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "form" | ... 264 more ... | "onTransitionEndCapture"> & { ...; }, any>' 

Ho can I use styled-components with TypeScript?

2

2 Answers 2

22

Use styled-components with typescript:

const Button = styled.button<{ primary?: boolean }>` 

Full code:

import * as React from 'react'; import styled from 'styled-components'; interface IProps{ primary?: boolean } const App:React.FC<IProps> = () => { return ( <div className="App"> <h1>Styled Components</h1> <Button>Normal</Button> <Button primary>Primary</Button> </div> ); } const Button = styled.button<{ primary?: boolean }>` background: ${props => props.primary ? 'red' : 'white'}; color: ${props => props.primary ? 'white' : 'red'}; font-size: 1em; margin: 1em; padding: 0.25em 1em; border: 1px solid green; border-radius: 3px; ` export default App; 

Edit sweet-pasteur-f3kfe

Sign up to request clarification or add additional context in comments.

2 Comments

I'm now getting the error that's on your CodeSandbox but my app won't show at all. The error is in the index.tsx - Property 'primary' is missing in type '{}' but required in type 'IProps'.ts(2741)
I fixed it with primary?: boolean in the interface
2

I prepare a example from my project

Wrapper.ts(styled-component)

import styled from 'styled-components'; interface Props { height: number; } export const Wrapper = styled.div<Props>` padding: 5%; height: ${(props) => props.height}%; `; 

index.tsx

import React, { FunctionComponent } from 'react'; import { Wrapper } from './Wrapper'; interface Props { className?: string; title: string; height: number; } export const MainBoardList: FunctionComponent<Props> = ({ className, title, height }) => ( <Wrapper height={height} className={className}> {title} </Wrapper> ); 
  1. you can import interface/type from 'index.tsx' to 'Wrapper.ts' to reuse.

  2. other wise you can specify type like this

    export const Wrapper = styled.div<{height:number}>`

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.