Skip to content

Conversation

@luicfrr
Copy link

@luicfrr luicfrr commented Apr 25, 2025

Motivation

With this change I can create my own typed custom text component.
Eg:

import {
  customText,
  useTheme,
  TextComponent,
  MD3Theme, 
  MD3TypescaleKey
} from 'react-native-paper'
import { MD3Type } from 'react-native-paper/lib/typescript/types'

enum CustomTextVariantType {
  'titleSmaller'
}
type CustomTextVariantsKeysType = keyof typeof CustomTextVariantType
type DefaultTextVariantsKeysType = keyof typeof MD3TypescaleKey
export type TextVariantsType<T = any> = {
  [ key in CustomTextVariantsKeysType ]: T
} & {
  [ key in DefaultTextVariantsKeysType ]?: T
}

export type CustomThemeType = Omit<MD3Theme, 'fonts'> & {
  fonts: TextVariantsType<MD3Type>
}

type VariantType = keyof typeof CustomTextVariantType
type ComponentType = {
  variant: VariantType
} & Props

function CustomText( {
  children,
  variant
}: ComponentType ): JSX.Element {
  const { fonts } = useTheme<CustomThemeType>()
  const list: TextVariantsType<TextComponent<CustomTextVariantType>> = {
    titleSmaller: customText<CustomTextVariantType.titleSmaller>()
  }
  const Component = list[ variant ]

  return <Component
    style={ {
      ...fonts[ variant ]
    } }
  >
    { children }
  </Component>
}

export default CustomText

luicfrr added 3 commits April 25, 2025 09:11
importing TextComponent type from new exported path
@callstack-bot
Copy link

Hey @luicfrr, thank you for your pull request 🤗. The documentation from this branch can be viewed here.

@lukewalczak
Copy link
Member

Hey @luicfrr, I might not fully grasp your use case, but if you're looking to create a CustomText component with custom variants, you can do it like this:

// CustomText.tsx

import { customText } from 'react-native-paper';

type CustomVariant = 'titleBigger' | 'titleSmaller';

export const CustomText = customText<CustomVariant>();

// theme
  titleSmaller: {
    color: 'red',
    fontSize: 48,
  },

  titleBigger: {
    color: 'blue',
    fontSize: 56,
  },

so in the result you will have a Paper's Text with predefined variants, along with new variants such as titleSmaller and titleBigger

Zrzut ekranu 2025-05-5 o 13 05 57

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants