import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
// initial state goes here
};
}
componentDidMount() {
// code to run after the component is mounted
}
componentDidUpdate(prevProps, prevState) {
// code to run after the component updates
}
componentWillUnmount() {
// code to run before the component is unmounted
}
handleClick() {
// event handler for click events
}
render() {
return (
<div>
{/* JSX code goes here */}
</div>
);
}
}
export default MyComponent;
Class components are made using ES6 classes. Function components are more often used and recommended. Function components are covered in this cheatsheet.
import React from 'react';
export class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
render() {
return (
<div>
{this.state.date.toLocaleTimeString()}
</div>
);
}
componentDidMount() {
this.intervalID = setInterval(() => {
this.setState({ date: new Date() });
}, 1000);
}
componentDidUpdate(prevProps, prevState) {
// Check if the state has changed before updating the component
if (prevState.date !== this.state.date) {
console.log('Component updated with a new date.');
}
}
componentWillUnmount() {
clearInterval(this.intervalID);
}
};
A component's lifecycle is when a component gets created, rendered, added to the DOM, updated, and removed. Steps part of a component's lifecycle.
class Counter extends React.Component {
constructor(){
super();
this.state = {
// initial state
score: 0
};
}
/* to change state, let's React know state
has changed and re-renders component */
// this.setState({score: this.state.score + 1});
// passing in a callback with a parameter to use previous state
/* this.setState((prevState) => ({
score: prevState.score + 1
})); // wrap the body in parentheses to return
} */
render(){
return (
<div>
<button className="decrement-button"> - </button>
<span className="score-counter">{ this.state.score }</span>
<button className="increment-button"> + </button>
</div>
)
}
};
Example showing and using state inside a class component. Use the state setter to update state.
class Counter extends React.Component {
constructor(){
super();
this.state = { score: 0 };
// this.incrementScore = this.incrementScore.bind(this);
}
increment = () => {
this.setState((prevState) => ({
score: prevState.score + 1
}));
}
decrement = () => {
this.setState((prevState) => ({
score: prevState.score - 1
}));
}
render(){
return (
<div>
<button className="decrement-button" onClick={this.decrement}> - </button>
<span className="score-counter">{ this.state.score }</span>
<button className="increment-button" onClick={this.increment}> + </button>
/* <button className="increment-button" onClick={this.increment.bind(this)}> + </button> - bind this inside handlers */
/* <button className="increment-button" onClick={() => this.increment()}> + </button> - use arrows function's lexical scope */
</div>
)
}
};
To make and handle events in class components. Not binded to class components by default, need to bind your custom methods to the class, so that this refers to component instance.
import React, { Component } from 'react';
class Product extends Component {
render() {
const { name, price, description } = this.props;
return (
<div className="product">
<h2>{name}</h2>
<p>{description}</p>
<p>Price: ${price}</p>
</div>
);
}
}
export default Product;
// ./App.js
import React from 'react';
import Product from './Product';
class App extends React.Component {
render() {
return (
<div>
<Product
name="Smartphone"
price={499.99}
description="A high-end smartphone with advanced features."
/>
<Product
name="Laptop"
price={1099.99}
description="Powerful laptop for work and entertainment."
/>
<Product
name="Headphones"
price={149.99}
description="Noise-cancelling headphones with premium sound quality."
/>
</div>
);
}
}
export default App;
Using props in class components.