skip to Main Content

I’m creating some custom components for my application and they essentially have some base styling done to them for light/dark modes. My goal is to be able to use those components with all their props later when the custom component is being used to stay flexible. How do I achieve this?

For example if I style a custom input component and use it, I want to be able to tap into the secureTextEntry prop when needed. Here is an example of what I have right now for my CustomText. I want to be able to style this further when needed.

import { Text, useColorScheme } from 'react-native';
import React from 'react';

type CustomTextProps = {
  text: string;
};

const CustomText = ({ text }: CustomTextProps) => {
  const isDarkMode = useColorScheme() === 'dark';

  return <Text style={{ color: isDarkMode ? '#fff' : '#000' }}>{text}</Text>;
};

export default CustomText;

2

Answers


  1. This sounds like a job for React Context which acts as a store for global state that you can access using useContext hook

    Login or Signup to reply.
  2. react-native expose interfaces for each component.
    so you need to extend your interface with TextProps:

    import { Text, TextProps } from 'react-native';
    
    interface CustomTextProps extends TextProps {
      text: string;
    };
    

    By extending those interfaces (e.g. TextProps) in CustomTextProps we can have all text element props passed to this component.

    Instead of having to declare each one we can just use a spread attribute ...rest

    const CustomText = ({ text, ...rest }: CustomTextProps) => {
      const isDarkMode = useColorScheme() === 'dark';
    
      return <Text style={{ color: isDarkMode ? '#fff' : '#000' }} {...rest}>{text}</Text>;
    };
    
    export default CustomText;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search