React Class Components
There are two kinds of components in React - function components and class components. Function components and hooks are the modern way of writing React but there are still a lot of legacy codebases using class components so it's still a must-know for any React developer.
Basic component
Class components must inherit from
Component
and have a render method that returnsjsx
We can access props through
this.props
import { Component } from "react";
class AdoptionListing extends Component {
render() {
const { name, imageURL } = this.props;
return (
<div className="kitten">
<h3>{name}</h3>
<img src={imageURL} alt="Kitten" />
<p>{name} is available for adoption</p>
<button>Adopt</button>
</div>
);
}
}
const App = () => {
return (
<>
<AdoptionListing name="Mittens" imageURL="http://placekitten.com/200/150" />
<AdoptionListing name="Bobo" imageURL="http://placekitten.com/201/150" />
<AdoptionListing name="Mickey" imageURL="http://placekitten.com/202/150" />
</>
);
};
State & Event Handlers
Initialise the state object either using a
constructor
or the simpler field declaration syntaxAccess state through
this.state
Update state through
this.setState
(same immutable update rules apply)Define event handlers as a method and use an arrow function to bind
this
to the instance
import { Component } from "react";
class AdoptionListing extends Component {
state = {
adopted: false,
};
adopt = () => {
this.setState({ adopted: true });
};
render() {
const { name, imageURL } = this.props;
return (
<div className="kitten">
<h3>{name}</h3>
<img src={imageURL} alt="Kitten" />
<p>
{name}
{this.state.adopted
? " has been adopted!"
: " is available for adoption"}
</p>
{!this.state.adopted && <button onClick={this.adopt}>Adopt</button>}
</div>
);
}
}
Last updated
Was this helpful?