### Install Prettier, Husky, and lint-staged for React Projects Source: https://github.com/typescript-cheatsheets/react/blob/main/docs/advanced/misc-concerns.md Installs the necessary development dependencies for code formatting and pre-commit hooks in a React project using npm or yarn. ```bash $ yarn add -D prettier husky lint-staged ``` -------------------------------- ### Configure TypeScript Project References Source: https://github.com/typescript-cheatsheets/react/blob/main/docs/advanced/patterns_by_version.md Provides configuration examples for tsconfig.json to enable project references, allowing large codebases to be split into smaller, independently compilable subprojects. ```json { "compilerOptions": { "composite": true, "declaration": true, "declarationMap": true, "rootDir": "." }, "include": ["./**/*.ts"], "references": [ { "path": "../myreferencedproject", "prepend": true } ] } ``` -------------------------------- ### Install and Use dts-gen for Autogenerating Types Source: https://github.com/typescript-cheatsheets/react/blob/main/docs/basic/troubleshooting/types.md This bash command demonstrates how to install the 'dts-gen' tool globally and then use it to generate TypeScript declaration files for a given module. This is useful when TypeScript's `--allowJs` and `--declaration` flags are insufficient. ```bash npm install -g dts-gen dts-gen -m ``` -------------------------------- ### Install ESLint and TypeScript ESLint Dependencies Source: https://github.com/typescript-cheatsheets/react/blob/main/docs/basic/linting.md Installs the necessary ESLint packages and TypeScript ESLint plugins for your project using Yarn. These are development dependencies. ```bash yarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint ``` -------------------------------- ### Modal Component Usage Example Source: https://github.com/typescript-cheatsheets/react/blob/main/README.md Demonstrates how to use the Modal component in a React application. It includes state management to control modal visibility and provides a basic structure for modal content and a close button. Assumes the existence of a 'modal-root' div in the static HTML. ```tsx import { useState } from "react"; function App() { const [showModal, setShowModal] = useState(false); return (
{/* you can also put this in your static html file */} {showModal && (
I'm a modal!{" "}
)} {/* rest of your app */}
); } ``` -------------------------------- ### Modal Component Usage Example Source: https://github.com/typescript-cheatsheets/react/blob/main/docs/basic/getting-started/portals.md Demonstrates how to use the Modal component in a React application. It includes state management to control modal visibility and provides a basic structure for the modal content and a button to trigger its display. ```tsx import { useState } from "react"; function App() { const [showModal, setShowModal] = useState(false); return (
// you can also put this in your static html file {showModal && (
I'm a modal!{" "}
)} // rest of your app
); } ``` -------------------------------- ### Legacy forwardRef Pattern (React 18 and earlier) Source: https://github.com/typescript-cheatsheets/react/blob/main/README.md Demonstrates the use of forwardRef to pass refs to child components. Includes examples of both mutable and immutable ref typing. ```tsx import { forwardRef, ReactNode, Ref } from "react"; interface Props { children?: ReactNode; type: "submit" | "button"; } export const FancyButton = forwardRef( (props: Props, ref: Ref) => ( ) ); ``` -------------------------------- ### Define Component Props and Structure Source: https://github.com/typescript-cheatsheets/react/blob/main/docs/hoc/excluding-props.md Example of standard React components that require an 'owner' prop, which will eventually be injected by a Higher-Order Component. ```tsx type DogProps = { name: string owner: string } function Dog({name, owner}: DogProps) { return
Woof: {name}, Owner: {owner}
} type CatProps = { lives: number; owner: string; }; function Cat({ lives, owner }: CatProps) { return (
Meow: {lives}, Owner: {owner}
); } ``` -------------------------------- ### Base HOC Example with React and TypeScript Source: https://github.com/typescript-cheatsheets/react/blob/main/docs/hoc/index.md A foundational Higher Order Component (HOC) example written in React and TypeScript. This HOC wraps a given component, optionally memoizes it, and enhances its display name for React DevTools. It supports custom prop comparison for memoization and aims to provide type safety. ```typescript type PropsAreEqual

= ( prevProps: Readonly

, nextProps: Readonly

) => boolean; const withSampleHoC =

( component: { (props: P): Exclude; displayName?: string; }, propsAreEqual?: PropsAreEqual

| false, componentName = component.displayName ?? component.name ): { (props: P): React.JSX.Element; displayName: string; } => { function WithSampleHoc(props: P) { //Do something special to justify the HoC. return component(props) as React.JSX.Element; } WithSampleHoc.displayName = `withSampleHoC(${componentName})`; let wrappedComponent = propsAreEqual === false ? WithSampleHoc : React.memo(WithSampleHoc, propsAreEqual); //copyStaticProperties(component, wrappedComponent); return wrappedComponent as typeof WithSampleHoc }; ``` -------------------------------- ### Component Usage with Injected Props (TypeScript) Source: https://github.com/typescript-cheatsheets/react/blob/main/docs/hoc/full-example.md Shows how a React component is defined to accept injected props from an HOC. It extends a base props interface with the injected props and demonstrates their usage within the component. ```typescript interface Props extends WithThemeProps { children?: React.ReactNode; } class MyButton extends React.Component { public render() { // Render an the element using the theme and other props. } private someInternalMethod() { // The theme values are also available as props here. } } export default withTheme(MyButton); ``` -------------------------------- ### Generic Component with Manual Ref Handling Source: https://github.com/typescript-cheatsheets/react/blob/main/docs/basic/getting-started/forward-create-ref.md Provides an example of a generic React component (`ClickableList`) where the ref is manually passed as a prop. This approach is necessary because TypeScript cannot automatically infer refs for generic components. ```tsx interface ClickableListProps { items: T[]; onSelect: (item: T) => void; mRef?: React.Ref | null; } export function ClickableList(props: ClickableListProps) { return (

); } ``` -------------------------------- ### Redux Reducer Typing with TypeScript Source: https://github.com/typescript-cheatsheets/react/blob/main/docs/basic/getting-started/hooks.md Shows how to integrate the `useReducer` example with the `Reducer` type from the `redux` library. This helper simplifies type management for reducer functions. ```tsx import { Reducer } from 'redux'; export function reducer: Reducer() {} ``` -------------------------------- ### Creating Anchor and Link Buttons in React with TypeScript Source: https://github.com/typescript-cheatsheets/react/blob/main/docs/advanced/patterns_by_usecase.md Defines `AnchorButton` and `LinkButton` components using React and TypeScript. `AnchorButton` renders an 'a' tag, while `LinkButton` renders a `NavLink`. Includes examples of their usage and a note on potential type errors. ```typescript const AnchorButton: React.FunctionComponent = (props) => ( ); } ``` -------------------------------- ### Basic ESLint Configuration for TypeScript Libraries (.eslintrc.js) Source: https://github.com/typescript-cheatsheets/react/blob/main/docs/basic/linting.md A foundational ESLint configuration file for TypeScript libraries. It sets up the environment, extends recommended rules, specifies the TypeScript parser, and defines custom rules for indentation, line endings, quotes, and unused variables. ```javascript module.exports = { env: { es6: true, node: true, jest: true, }, extends: "eslint:recommended", parser: "@typescript-eslint/parser", plugins: ["@typescript-eslint"], parserOptions: { ecmaVersion: 2017, sourceType: "module", }, rules: { indent: ["error", 2], "linebreak-style": ["error", "unix"], quotes: ["error", "single"], "no-console": "warn", "no-unused-vars": "off", "@typescript-eslint/no-unused-vars": [ "error", { vars: "all", args: "after-used", ignoreRestSiblings: false }, ], "@typescript-eslint/explicit-function-return-type": "warn", // Consider using explicit annotations for object literals and function return types even when they can be inferred. "no-empty": "warn", }, }; ``` -------------------------------- ### Function as Child Render Prop Type (TypeScript/React) Source: https://github.com/typescript-cheatsheets/react/blob/main/docs/advanced/patterns_by_usecase.md Define the type for a render prop that accepts a function as its child. This pattern is useful for passing down state or callbacks to child components. The example shows an interface where `children` is a function that returns `ReactNode`. ```typescript import { ReactNode } from "react"; interface Props { children: (foo: string) => ReactNode; } ``` -------------------------------- ### Typing Exported Hooks in TypeScript Source: https://github.com/typescript-cheatsheets/react/blob/main/README.md Demonstrates how to define type declarations for React hooks, including input props and return props. This approach assumes you have a type declaration file and access to the hook's source code, typically found in an index.js file. ```typescript declare module 'use-untyped-hook' { export interface InputProps { ... } // type declaration for prop export interface ReturnProps { ... } // type declaration for return props export default function useUntypedHook( prop: InputProps // ... ): ReturnProps; } ``` ```javascript // ... const useUntypedHook = (prop) => { // some processing happens here return { /* ReturnProps */ }; }; export default useUntypedHook; ``` -------------------------------- ### Typing getDerivedStateFromProps to Determine State Type (TypeScript) Source: https://github.com/typescript-cheatsheets/react/blob/main/docs/basic/getting-started/class-components.md This example shows how to infer the component's state type directly from the return type of `getDerivedStateFromProps`. This approach is dynamic and ensures the state type always matches what the method returns. ```tsx class Comp extends React.Component< Props, ReturnType > { static getDerivedStateFromProps(props: Props) {} } ``` -------------------------------- ### Wrapping HTML Elements with ComponentPropsWithoutRef Source: https://github.com/typescript-cheatsheets/react/blob/main/docs/advanced/patterns_by_usecase.md Demonstrates how to create a wrapper component that inherits native HTML element props while adding custom properties. This approach ensures type safety for standard attributes like 'type'. ```tsx export interface ButtonProps extends React.ComponentPropsWithoutRef<"button"> { specialProp?: string; } export function Button(props: ButtonProps) { const { specialProp, ...rest } = props; // do something with specialProp return