react-component-writing
React component style guide
When & Why to Use This Skill
This Claude skill provides a comprehensive React component style guide designed to enhance code consistency and maintainability. It defines strict standards for named exports, arrow functions, and GraphQL component separation, while offering best practices for internationalization and Jest testing to ensure high-quality, type-safe software engineering.
Use Cases
- Standardizing React Development: Enforce a consistent coding style across a project by following specific rules for component exports and arrow function declarations.
- Architecting GraphQL Components: Improve code modularity by separating UI presentation from GraphQL data logic, making components easier to manage and refactor.
- Type-Safe Internationalization: Implement robust multi-language support using the recommended useFormatMessage hook, ensuring proper typing for all localized strings.
- Streamlining Unit Testing: Utilize proven patterns for testing GraphQL-wrapped components with Jest, including both UI-direct testing and mock-based approaches.
| name | react-component-writing |
|---|---|
| description | React component style guide |
React components
Guidelines
- Export a named variable
export const ExampleComponent. Avoid default exports. - Avoid spread props
{...props}in GraphQL wrapper components. List all the props individually to improve type safety and linting. - Format the component function as a plain arrow function. Do not type with
React.FC.
UI components
For components that do not use GraphQL queries, writing UI components is straightforward. See example example-ui-component.tsx.
GraphQL components
For components that use GraphQL queries, component structure is separated into two components: the UI sub-component ExampleComponentUI and the GraphQL wrapper component, ExampleComponent. See example example-graphql-component.tsx.
Jest tests with GraphQL components
Jest tests for GraphQL components can be written in two ways:
- Test the UI sub-component, set props directly. See example-graphql-component-ui.spec.tsx
- Add GraphQL mocks. See example-graphql-component-mocks.spec.tsx
Internationalization
Most components use MessageFormat type to render internationalization text.
To render MessageFormat to a string, use useFormatMessage from Commonplace, as it is properly typed for MessageFormat. Do not use useIntl from react-intl.
import { Text, useFormatMessage } from '$commons/app/shared/commonplace';
const Component = ({ pageNumber }: { pageNumber: number }) => {
const formatMessage = useFormatMessage();
const nextText = formatMessage({ id: 'shared.next' });
return <Text text={`${nextText}: ${pageNumber}`} />;
};