Skip to content

Instantly share code, notes, and snippets.

@gchumillas
Last active November 14, 2023 20:12
Show Gist options
  • Save gchumillas/3da3b8f03296181e438a77f8adf9c125 to your computer and use it in GitHub Desktop.
Save gchumillas/3da3b8f03296181e438a77f8adf9c125 to your computer and use it in GitHub Desktop.
React Native: how to extend Text component (the "hook" and the "class" way).
import React from 'react'
import { Text, TextProps } from 'react-native'
// The "hook" way.
// The `React.PropsWithChildren` type adds the `children` property to the `TextProps` type.
const AppText1 = ({ children, style, ...rest }: React.PropsWithChildren<TextProps>) => (
<Text style={[{ fontFamily: 'monospace' }, style]} {...rest}>
{children}
</Text>
)
// The "class" way.
// The `React.Component<TextProps>` extends the `Text` component.
class AppText2 extends React.Component<TextProps> {
render() {
const { children, style, ...rest } = this.props
return (
<Text style={[{ fontFamily: 'monospace' }, style]} {...rest}>
{children}
</Text>
)
}
}
@facuescobar
Copy link

Thank you, I was trying to create a custom text component but typescript was complaining about my props, and this React.PropsWithChildren<TextProps>) fixed that problem.

@deepakaggarwal7
Copy link

Give error = Type '{}' is not assignable to type 'Text'.
Type '{}' is missing the following properties from type 'NativeMethods': measure, measureInWindow, measureLayout, setNativeProps, and 3 more.

@bpoulaindev
Copy link

Thanks a lot that really helped me out !

@russocorp
Copy link

Tks :)

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