React Class-based components

up:: React Components

  • You can build everything with class-based components but functional components are generally easier.
  • Components based on JavaScript Classes
  • Traditionally, you had to use class-based components in some contexts but it’s not longer necessary.
  • Functional components are the default and modern approach.
  • Class-based components cannot use React Hooks
class Product extends Component {
	render() {
		return <h2>A product</h2>
	}
}
  • In class-based components, your state always is an object.
import { Component } from 'react';
 
class Product extends Component {
	this.state = {
		showUsers: true,
		more: 'test',
	},
	render() {
		return <h2>A product</h2>
	}
}

To change state:

toggleUsersHandler() {
	this.setState({showUsers: false})
}

Error boundaries

Ensures that not the whole application crashes. This only works in class-based components (for now).

class ErrorBoundary extends Component {
	constructor() {
		super();
		this.state = { hasError; false }
	}
	componentDidCatch(error) {
		this.setState({ hasError: true });
	}
 
	render () {
		if (this.state.hasError) {
			return <p>Something went wrong</p>;
		}
		return this.props.children;
	}
}