Rules
no-class-component
Disallows class components except for error boundaries.
Full Name in eslint-plugin-react-x
react-x/no-class-componentFull Name in @eslint-react/eslint-plugin
@eslint-react/no-class-componentPresets
strict
strict-typescript
strict-type-checked
Rule Details
Component is the base class for React components defined as JavaScript classes. Class components are still supported by React, but we don’t recommend using them in new code.
We recommend defining components as functions instead of classes. See how to migrate.
Common Violations
Invalid
import React from "react";
interface MyComponentProps {
name: string;
}
class MyComponent extends React.Component<MyComponentProps> {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}Valid
interface MyComponentProps {
name: string;
}
function MyComponent({ name }: MyComponentProps) {
return <h1>Hello, {name}!</h1>;
}import React, { Component } from "react";
interface ErrorBoundaryProps {
children: React.ReactNode;
}
// This is an exception to the rule, as ErrorBoundary is a special case.
class ErrorBoundary extends Component<ErrorBoundaryProps> {
state = { hasError: false };
static getDerivedStateFromError(error: Error) {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}Resources
Further Reading
See Also
react-x/no-component-will-mount
Replaces usage ofcomponentWillMountwithUNSAFE_componentWillMount.react-x/no-component-will-receive-props
Replaces usage ofcomponentWillReceivePropswithUNSAFE_componentWillReceiveProps.react-x/no-component-will-update
Replaces usage ofcomponentWillUpdatewithUNSAFE_componentWillUpdate.react-x/no-unsafe-component-will-mount
Warns about the use ofUNSAFE_componentWillMountin class components.react-x/no-unsafe-component-will-receive-props
Warns about the use ofUNSAFE_componentWillReceivePropsin class components.react-x/no-unsafe-component-will-update
Warns about the use ofUNSAFE_componentWillUpdatein class components.