Table of contents
Introduction
In class-based components first, we need to create a class by using the
class
keyword and then extend it to react. component usingextends
.react.component
will be imported from react.The only compulsory method in this class is
render
which will return some JSX which will be added to the dom.Passing props in class- based components
example:
// Parent component class ParentComponent extends React.Component { render() { const message = "Hello, world!"; return ( <ChildComponent message={message} /> ); }Creat } // Child component class ChildComponent extends React.Component { render() { return ( <div>{this.props.message}</div>//passed in a prop ); } }
In a React class component, you can create and manage multiple states using the
setState
method provided by theComponent
base class.class MyComponent extends React.Component { constructor(props) { super(props); this.state = { name: "John", age: 25, isStudent: true }; } render() { return ( <div> <p>Name: {this.state.name}</p> <p>Age: {this.state.age}</p> <p>Student: {this.state.isStudent ? "Yes" : "No"}</p> </div> ); } }
In class-based React components, you can update the component's state by calling the
setState()
method provided by theComponent
base class.class MyComponent extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState({ count: this.state.count + 1 }); } render() { return ( <div> <p>Count: { this.state.count // for multiple states update here only }</p> <button onClick={this.handleClick}>Increment</button> </div> ); } }
Do not do this:
this.state.count=10 // not preferred