Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - styled-components, props, and TypeScript

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?

like image 536
lomine Avatar asked Apr 17 '26 05:04

lomine


1 Answers

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

like image 82
keikai Avatar answered Apr 18 '26 18:04

keikai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!