- Spec files
npm-react
Describes: pkg:npm/react@19.1.x
- Description
- React is a JavaScript library for building user interfaces with a declarative, component-based approach.
- Author
- tessl
- Last updated
components.md docs/
1# Components and Elements23Core component classes and element creation functions for building React applications. This includes base classes for creating stateful and stateless components, as well as functions for creating and manipulating React elements.45## Capabilities67### Component Class89Base class for React components with state and lifecycle methods.1011```typescript { .api }12/**13* Base class for React components14*/15class Component<P = {}, S = {}> {16constructor(props: P, context?: any);1718/**19* Updates component state and triggers re-render20* @param state - Partial state update or function returning state update21* @param callback - Optional callback executed after state update22*/23setState<K extends keyof S>(24state: ((prevState: Readonly<S>, props: Readonly<P>) => (Pick<S, K> | S | null)) | (Pick<S, K> | S | null),25callback?: () => void26): void;2728/**29* Forces component to re-render immediately30* @param callback - Optional callback executed after re-render31*/32forceUpdate(callback?: () => void): void;3334/**35* Renders the component's UI36* @returns React node representing the component's UI37*/38render(): React.ReactNode;3940readonly props: Readonly<P>;41state: Readonly<S>;42context: any;43refs: { [key: string]: React.ReactInstance };44}45```4647**Usage Examples:**4849```typescript50import React, { Component } from "react";5152interface Props {53initialCount: number;54}5556interface State {57count: number;58}5960class Counter extends Component<Props, State> {61constructor(props: Props) {62super(props);63this.state = { count: props.initialCount };64}6566increment = () => {67this.setState({ count: this.state.count + 1 });68};6970render() {71return (72<div>73<p>Count: {this.state.count}</p>74<button onClick={this.increment}>Increment</button>75</div>76);77}78}79```8081### PureComponent Class8283Component class with built-in shallow comparison for props and state to prevent unnecessary re-renders.8485```typescript { .api }86/**87* Component with automatic shallow comparison optimization88* Only re-renders when props or state change shallowly89*/90class PureComponent<P = {}, S = {}> extends Component<P, S> {}91```9293**Usage Examples:**9495```typescript96import React, { PureComponent } from "react";9798interface Props {99name: string;100age: number;101}102103class UserCard extends PureComponent<Props> {104render() {105return (106<div>107<h3>{this.props.name}</h3>108<p>Age: {this.props.age}</p>109</div>110);111}112}113```114115### Fragment116117Wrapper component that groups multiple elements without adding extra DOM nodes.118119```typescript { .api }120/**121* Groups multiple children without creating DOM wrapper122*/123const Fragment: React.ExoticComponent<{ children?: React.ReactNode }>;124```125126**Usage Examples:**127128```typescript129import React, { Fragment } from "react";130131function UserInfo() {132return (133<Fragment>134<h1>User Profile</h1>135<p>Welcome back!</p>136</Fragment>137);138}139140// Short syntax141function UserInfoShort() {142return (143<>144<h1>User Profile</h1>145<p>Welcome back!</p>146</>147);148}149```150151### StrictMode152153Development tool that helps identify potential problems in React applications.154155```typescript { .api }156/**157* Development mode helper for highlighting potential problems158* Activates additional checks and warnings for descendants159*/160const StrictMode: React.ExoticComponent<{ children?: React.ReactNode }>;161```162163**Usage Examples:**164165```typescript166import React, { StrictMode } from "react";167168function App() {169return (170<StrictMode>171<Header />172<Main />173<Footer />174</StrictMode>175);176}177```178179### Profiler180181Component for measuring performance of React component trees.182183```typescript { .api }184/**185* Measures rendering performance of its descendants186*/187interface ProfilerProps {188id: string;189onRender: (190id: string,191phase: "mount" | "update",192actualDuration: number,193baseDuration: number,194startTime: number,195commitTime: number,196interactions: Set<any>197) => void;198children?: React.ReactNode;199}200201const Profiler: React.ExoticComponent<ProfilerProps>;202```203204### createElement205206Creates React elements programmatically without JSX.207208```typescript { .api }209/**210* Creates a React element211* @param type - Element type (string for DOM elements, component for custom components)212* @param props - Element properties213* @param children - Child elements214* @returns React element215*/216function createElement<P extends {}>(217type: string | React.ComponentType<P>,218props?: (P & React.Attributes) | null,219...children: React.ReactNode[]220): React.ReactElement<P>;221```222223**Usage Examples:**224225```typescript226import React, { createElement } from "react";227228// Create DOM element229const heading = createElement("h1", { className: "title" }, "Hello World");230231// Create component element232const button = createElement(233"button",234{ onClick: () => console.log("clicked") },235"Click Me"236);237238// Create custom component element239function Welcome(props: { name: string }) {240return createElement("h1", null, `Hello, ${props.name}!`);241}242243const welcome = createElement(Welcome, { name: "Alice" });244```245246### cloneElement247248Clones and returns a new React element using the original element as the starting point.249250```typescript { .api }251/**252* Clones a React element with new props253* @param element - Element to clone254* @param props - Additional or replacement props255* @param children - New children (replaces existing children)256* @returns Cloned React element257*/258function cloneElement<P>(259element: React.ReactElement<P>,260props?: Partial<P> & React.Attributes,261...children: React.ReactNode[]262): React.ReactElement<P>;263```264265**Usage Examples:**266267```typescript268import React, { cloneElement } from "react";269270function Button(props: { className?: string; onClick?: () => void; children: React.ReactNode }) {271return <button {...props}>{props.children}</button>;272}273274function App() {275const originalButton = <Button onClick={() => alert("clicked")}>Original</Button>;276277// Clone with additional props278const clonedButton = cloneElement(originalButton, {279className: "primary",280children: "Cloned Button"281});282283return (284<div>285{originalButton}286{clonedButton}287</div>288);289}290```291292### isValidElement293294Verifies whether an object is a valid React element.295296```typescript { .api }297/**298* Checks if object is a valid React element299* @param object - Object to test300* @returns True if object is a React element301*/302function isValidElement(object: any): object is React.ReactElement;303```304305**Usage Examples:**306307```typescript308import React, { isValidElement } from "react";309310function renderContent(content: unknown) {311if (isValidElement(content)) {312return content;313}314315if (typeof content === "string") {316return <span>{content}</span>;317}318319return <span>Invalid content</span>;320}321322// Usage323const element = <div>Hello</div>;324const text = "Hello";325326console.log(isValidElement(element)); // true327console.log(isValidElement(text)); // false328```329330## Types331332### Component-Related Types333334```typescript { .api }335type ComponentType<P = {}> = ComponentClass<P> | FunctionComponent<P>;336337interface ComponentClass<P = {}, S = ComponentState> {338new (props: P, context?: any): Component<P, S>;339propTypes?: WeakValidationMap<P>;340contextTypes?: ValidationMap<any>;341childContextTypes?: ValidationMap<any>;342defaultProps?: Partial<P>;343displayName?: string;344}345346interface FunctionComponent<P = {}> {347(props: P, context?: any): ReactElement<any, any> | null;348propTypes?: WeakValidationMap<P>;349contextTypes?: ValidationMap<any>;350defaultProps?: Partial<P>;351displayName?: string;352}353354interface ReactElement<P = any, T = string | JSXElementConstructor<any>> {355type: T;356props: P;357key: Key | null;358ref: any;359}360361type ReactNode = ReactElement | string | number | boolean | null | undefined | ReactNode[];362363type Key = string | number;364365interface Attributes {366key?: Key | null;367}368369interface ClassAttributes<T> extends Attributes {370ref?: Ref<T>;371}372```