Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Color Type with TypeScript

I'm creating a simple component that accepts a color as a prop, and I'm using type script in my project and I want to force users to pass only valid color values to the component using type script type checking. how can I achieve this using react native? which types I should use?

const TextBody = ({
  color
}: {color: //Need This}) => {
  return (
    <Text
      style={[
        generalStyles,
        textTransformStyle,
        textAlignStyle,
        selfAlignmentStyle,
        typography?.body,
        style,
      ]}
    >
      {children}
    </Text>
  );
};

export { TextBody };

users should be able to pass colors like following

<TextBody color="red"/>
<TextBody color="#21292F"/>
<TextBody color={rgba(12,2,1,0)}/>

And this should throw an error

<TextBody color={5252}/>
like image 810
Ushan Fernando Avatar asked Oct 23 '25 00:10

Ushan Fernando


1 Answers

Sorry guys I found a solution but couldn't update the question for a long time,

To enforce type checking for valid color values in a React Native component using TypeScript, we can use the ColorValue type provided by React Native. This type represents a valid color value that can be used in styles.

Here's an example implementation for a TextBody component:

import { Text, TextStyle, ColorValue } from 'react-native';

interface TextBodyProps {
  color: ColorValue;
}

const TextBody: React.FC<TextBodyProps> = ({ color, children }) => {
  const textStyles: TextStyle[] = [
    generalStyles,
    textTransformStyle,
    textAlignStyle,
    selfAlignmentStyle,
    typography?.body,
    style,
  ];

  return (
    <Text style={[...textStyles, { color }]}>
      {children}
    </Text>
  );
};

export { TextBody };

In this example, the TextBodyProps interface is defined with the color prop of type ColorValue, which represents a valid color value for React Native styles.

Users can now pass valid color values as props, including color names, hex codes, and RGBA values, as shown in the following examples:

<TextBody color="red" />
<TextBody color="#21292F" />
<TextBody color="rgba(12, 2, 1, 0)" />

If a user tries to pass an invalid color value, such as a number (5252 in the example below), TypeScript will throw a type error:

<TextBody color={5252} /> // Throws a type error

Make sure to have the necessary TypeScript and React Native configurations in your project to enable type checking.

By using the ColorValue type, you can enforce type checking and ensure that only valid color values are passed to your React Native components.

like image 68
Ushan Fernando Avatar answered Oct 24 '25 14:10

Ushan Fernando