About
A React Class component is a React component created via a Javascript.
Even if class component are now an old technology, they are still used and are also still mandatory knowledge if you want to create an Error boundary (ie catch all error component)
Syntax
Javascript
class Welcome extends React.Component {
// Optional. Needed to set state
constructor(props) {
super(props); // Always call the base constructor with props.
}
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Feature available only to classes:
Typescript
type MyProps = {
name: string,
children: React.ReactNode
}
class Welcome extends React.Component<MyProps> {
// Optional. Needed to set state
constructor(props:MyProps) {
super(props); // Always call the base constructor with props.
this.state = ...
}
render() {
return (
<>
<h1>Hello, {this.props.name}</h1>
{children}
</>
);
}
}