Using the Text component in React simplifies the management of styles and semantics for different types of text in an application. By encapsulating style logic and HTML tags within a reusable component, design consistency is improved, and code maintenance is facilitated. Additionally, the component's flexibility allows for customization and extension of styles through additional props, promoting greater coherence and adaptability in text content presentation. This is especially useful in large applications where a uniform and easily modifiable style is required for various text elements.
export const textStyles = {
title: {
fontSize: '2em',
fontWeight: 'bold',
margin: '0.5em 0',
},
subtitle: {
fontSize: '1.5em',
fontWeight: 'semi-bold',
margin: '0.4em 0',
},
body: {
fontSize: '1em',
fontWeight: 'normal',
margin: '0.3em 0',
},
paragraph: {
fontSize: '1em',
fontWeight: 'normal',
margin: '0.3em 0',
},
small: {
fontSize: '0.8em',
fontWeight: 'normal',
margin: '0.2em 0',
},
tiny: {
fontSize: '0.6em',
fontWeight: 'normal',
margin: '0.1em 0',
},
};
import React, { CSSProperties, ReactNode } from 'react';
import { textStyles } from './TextStyles';
type TextType = 'title' | 'subtitle' | 'body' | 'paragraph' | 'small' | 'tiny';
type TextAlign = 'left' | 'center' | 'right' | 'justify';
interface TextProps {
type?: TextType;
children: ReactNode;
style?: CSSProperties;
color?: string;
align?: TextAlign;
fontFamily?: string;
margin?: string;
padding?: string;
[key: string]: any;
}
const Text: React.FC<TextProps> = ({
type = 'body',
children,
style,
color,
align,
fontFamily,
margin,
padding,
...props
}) => {
const getTypeStyles = (type: TextType): CSSProperties => {
switch (type) {
case 'title':
return textStyles.title;
case 'subtitle':
return textStyles.subtitle;
case 'body':
return textStyles.body;
case 'paragraph':
return textStyles.paragraph;
case 'small':
return textStyles.small;
case 'tiny':
return textStyles.tiny;
default:
return textStyles.body; // Default style
}
};
const Element = type === 'title' ? 'h1' :
type === 'subtitle' ? 'h2' :
type === 'paragraph' ? 'p' :
'span'; // Default element
const styles: CSSProperties = {
...getTypeStyles(type),
color,
textAlign: align,
fontFamily,
margin,
padding,
...style,
};
return (
<Element style={styles} {...props}>
{children}
</Element>
);
};
export default Text;
import React from 'react';
import Text from './Text';
const App: React.FC = () => {
return (
<div>
<Text type="title" color="blue" align="center">This is a Title</Text>
<Text type="subtitle" color="green" fontFamily="Arial">This is a Subtitle</Text>
<Text type="body" margin="20px 0" padding="10px">This is body text.</Text>
<Text type="paragraph" align="justify">This is a paragraph.</Text>
<Text type="small">This is small text.</Text>
<Text type="tiny">This is tiny text.</Text>
</div>
);
};
export default App;