Class-Based Components in ReactJS
Summary:
In this document, you’ll learn how to create class-based components in ReactJS. These were used in older versions of ReactJS. The topics covered include managing state, accessing props, using context API with components, creating error boundaries, and more.
Excerpt:
Class-Based Components in React
Before React 16.8, we used to write components using both classes and functions.
But you could only declare the state in the class component and not in the functional
component.
You cannot use React hooks inside functional components. You cannot declare a state
in functional components in older React.
The class component in old React is simply an ES6 class defined in modern JavaScript.
You’ll have to extend (inherit) this class from the Component class imported from the
react library.
This base class Component provides the render() method inside this derived class. You
should use this method to return your JSX code which you would normally return
from a functional component.
This base class Component also provides access to other methods e.g. lifecycle
methods such as ComponentDidMount(), componentDidUpdate(),
componentWillUnmount(), componentWillReceiveProps() etc.
You should declare the constructor() function and call the super() method inside it so that it
calls the constructor() function of its base class.
INITIALIZING AND UPDATING STATE
State in-class components could only be initialized in the constructor of the class.
Later it could be updated using the this.setState() function.
State in class components is always declared as an object. You should use this
keyword before the state variable to point to the context of the class.
this.state.showUsers;
State in-class components is updated in a different way as compared to how it’s
updated in the functional components. State in class is not overridden completely;
only the relevant part is updated. Due to this reason, you can easily update the
relevant state slice without worrying about the other pieces of state. e.g.
this.setState({ showUsers: true });
If you want to update state based on the value of the previous state, then you’ll have to
pass the function inside this.setState() function which will return a new state object.
this.setState(prevState => {
return {
showUsers: !prevState.showUsers,
};
})
Reviews