code-snippets/docs/react-native/generic-text.md
Liam Pietralla 8ad5845efc
Some checks failed
Build, Test & Publish / Build and Publish Container Image (push) Has been cancelled
Build, Test & Publish / Deploy to Infrastructure (push) Has been cancelled
Build, Test & Publish / Build (push) Has been cancelled
initial commit
2024-09-05 13:54:08 +10:00

98 lines
2.1 KiB
Markdown

# Generic React Native Text
The generic text component is a useful tool so apply consistent styling to text components throughout your app. In this case, we'll create a `Text` component that allows us to apply consistent styling to text components.
## Component
::: code-group
```tsx:line-numbers [Text.tsx]
import { TextType } from './types';
import { ReactNode, forwardRef } from 'react';
import { Text as NativeText, TextStyle, StyleSheet, StyleProp } from 'react-native';
type TextProps = {
type?: TextType;
children: ReactNode;
style?: StyleProp<TextStyle>;
} & TextStyle;
const Text = forwardRef<NativeText, TextProps>(function Text(
{ type, children, style, ...restProps }: TextProps,
ref
) {
const textStyles = textStyle(type ?? 'standard', restProps);
return (
<NativeText ref={ref} style={[textStyles.text, style]}>
{children}
</NativeText>
);
});
const textStyle = (type: TextType, restProps: TextStyle) => {
let styles = {};
switch (type) {
case 'title':
styles = {
fontSize: 32,
fontWeight: 'bold',
color: 'black',
};
break;
case 'title2':
styles = {
fontSize: 25,
fontWeight: 'bold',
color: 'black',
};
break;
case 'subtitle':
styles = {
fontSize: 12,
fontWeight: 'normal',
color: 'darkgray',
};
break;
case 'link':
styles = {
fontSize: 14,
fontWeight: 'normal',
color: 'blue',
textDecorationLine: 'underline',
};
break;
case 'standard':
default:
styles = {
fontSize: 14,
fontWeight: 'normal',
color: 'black',
};
break;
}
return StyleSheet.create({
text: {
...styles,
...restProps,
},
});
};
export default Text;
```
```tsx:line-numbers [types.ts]
export type TextType = "standard" | "title" | "title2" | "subtitle" | "link";
```
:::
## Usage
```tsx
<Text type="title">Title</Text>
<Text type="subtitle">Subtitle</Text>
<Text type="link">Link</Text>
<Text>Standard</Text>
```