Search code examples
typescriptreact-nativestyled-componentsreact-typescript

Using types in Styled Component in Typescript


So, I'm working with React Native and never used Styled Components before.
When I'm creating a new component without SC, such a custom button, I do the following:

import React, { ReactNode } from 'react'
import { TouchableOpacity, TouchableOpacityProps} from 'react-native'

import styles from './styles'

type CustomButtonProps = TouchableOpacityProps & {
  children: ReactNode 
}

const CustomButton = ({ children, ...props }: CustomButtonProps) => {
  return (
    <TouchableOpacity style={styles.container} {...props}>
      {children}
    </TouchableOpacity>
  )
}

export { CustomButton }

This way, when I'm using my component in other place, I can pass all aditional TouchableOpacity props that's not listed in my custom props.

I want to know what type I use to replace the TouchableOpacityProps when I'm using Styled Components to continue using the non-listed props, as, if I use TouchableOpacityProps, it gets me an error saying the types doesn't match:

import React, { ReactNode } from 'react'

import { StyledTouchableOpacity } from './styles'

type CustomButtonProps = ??? & {
  children: ReactNode 
}

const CustomButton = ({ children, ...props }: CustomButtonProps) => {
  return (
    <StyledTouchableOpacity {...props}>
      {children}
    </StyledTouchableOpacity>
  )
}

export { CustomButton }

Thank you :)


Solution

  • Your props is correct. I think you are using styled.TouchableOpacity where TouchableOpacity is provided by styled-component and it will prompt you error as it is not compatible with react-native's TouchableOpacity

    So providing the react-native TouchableOpacity to styled can solve the type problem:

    import { TouchableOpacity, TouchableOpacityProps} from 'react-native'
    
    const StyledTouchableOpacity = styled(TouchableOpacity)`
      ...
    `
    

    Full Code:

    import React, { ReactNode } from 'react'
    import { TouchableOpacity, TouchableOpacityProps} from 'react-native'
    import styled from 'styled-components/native';
    
    const StyledTouchableOpacity = styled(TouchableOpacity)`
      padding-vertical: 16px;
      padding-horizontal: 24px;
    `;
    
    type CustomButtonProps = TouchableOpacityProps & {
        children: ReactNode 
    }
    
    const CustomButton = ({ children, ...props }: CustomButtonProps) => {
      return (
        <StyledTouchableOpacity {...props}>
          {children}
        </StyledTouchableOpacity>
      )
    }
    
    export { CustomButton }