- Introduction Now let’s learn about class components in React. Class components are another way to create components, and they can manage state and use lifecycle methods. Our characters, Geek and Gal, will help us understand class components with their fun interactions!
- Class Components
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
<Welcome name="Charlie" />
class JokeBox extends React.Component {
constructor(props) {
super(props);
this.state = {
joke: 'Why did the chicken cross the road? To get to the other side! 😂',
};
}
updateJoke() {
this.setState({
joke: 'Why couldn’t the bicycle stand up by itself? It was two-tired! 😂',
});
}
render() {
return (
<div>
<p>{this.state.joke}</p>
<button onClick={() => this.updateJoke()}>Update Joke</button>
</div>
);
}
}
- Conclusion Class components in React are based on JavaScript classes and can manage state and use lifecycle methods. They’re a bit more complex than functional components, but understanding them is essential for working with older projects or specific situations. Keep on learning, and you’ll become a React pro in no time! 🌟