react js-tutorial

React Class with example

The mainstay of the majority of contemporary web applications created with ReactJS are React class-based components. These are basic classes for the components (made up of multiple functions that add functionality to the application). The ReactJS Component class has child classes that are all class-based components.

Program used as an example to show how to create class-based components. Make a React app and change the App.js as follows:

Filename- App.js:

import React from "react";
class App extends React.Component {
  render() {
    return <h1>Learn Code Zone</h1>;
  }
}
export default App;

Once a component is declared, it can be used in other components. Program to demonstrate the use of class based components in other components.

Example: Open the App.js file and replace the code with the below code.

import React from "react";
class Sample extends React.Component {
  render() {
    return <h1>Learn Code Zone</h1>;
  }
}
class App extends React.Component {
  render() {
    return <Sample />;
  }
}
export default App;

The main feature of class-based components that distinguished them from functional components is that they have access to a state which dictates the current behavior and appearance of the component (Later, with React Hooks introduced in version 16.8, we are able to declare a stateful component without declaring a class). This state can be modified by calling the setState() function. One or more variables, arrays, or objects defined as part of the state can be modified at a time with the setState() function.

Example: Program to demonstrate the use of state in class-based components. Open the App.js file and replace the code with the below code.

import React from "react";
class App extends React.Component {
constructor(props) {
	super(props);
	this.state = { change: true };
}
render() {
	return (
	<div>
		<button
		onClick={() => {
			this.setState({ change: !this.state.change });
		}}
		>
		Click Here!
		</button>
		{this.state.change ? (
		<h1>Welcome to Learn Code Zone</h1>
		) : (
		<h1>A Computer Science Portal</h1>
		)}
	</div>
	);
}
}
export default App;

Output:

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.