Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using styled components with Typescript, prop does not exist?

Here is my styled component.

import * as React from 'react'; import styled from 'styled-components'; import { ComponentChildren } from 'app-types';  interface Props {     children: ComponentChildren;     emphasized: boolean; }  const HeadingStyled = styled.h2`     ${props => props.emphasized && css`         display: inline;         padding-top: 10px;         padding-right: 30px;   `} `;  const Heading = (props: Props) => (     <HeadingStyled>         {props.children}     </HeadingStyled> );  export default Heading; 

I get warnings that:

  • Property 'emphasized' does not exist on type 'ThemedStyledProps<DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement>, any>'.
  • Cannot find name 'css'. Did you mean 'CSS'?

How can I get this to work?

like image 448
user1283776 Avatar asked Sep 19 '18 11:09

user1283776


People also ask

Can you use props in styled-components?

To pass props to React components created with styled-components, we can interpolate functions into the string that creates the component. We create the ArrowStyled component with the styled. div tag. Then string that we pass into the tag has the rotate value set from a prop.

Can styled-components receive custom props?

The css prop is a convenient way to iterate on your components without settling on fixed component boundaries yet. It works on both normal HTML tags as well as components, and supports everything any styled component supports, including adapting based on props, theming and custom components.

Do styled-components work with TypeScript?

We need to install some dependencies because styled-components doesn't come with create-react-app. This installs the styled-components types for TypeScript as a dev dependency. We're also going to use Material Icons, so let's install the material-ui package .


1 Answers

  • The styled component will have to specify the prop to pass to the component like styled("h2")<IProps>. You can read more about the pattern from documentation
  • css is not required here, it is added as a helper when you need to actually return CSS from a function. Check out conditional rendering.

Taking these into account, the component becomes:

const HeadingStyled = styled("h2")<{emphasized: boolean}>`   ${props => props.emphasized && `     display: inline;     padding-top: 10px;     padding-right: 30px;   `} `; 

A use-case for css

like image 186
Agney Avatar answered Oct 05 '22 14:10

Agney