Class components in React.js are ES6 classes that extend from React.Component
and must contain a render
method that returns JSX. Here’s a step-by-step guide to creating and using class components in React:
Creating a Class Component
A class component is a JavaScript class that extends React.Component
and includes a render
method.
Create the Component File: Create a new file for your component, e.g., MyComponent.js
.
// src/MyComponent.jsx
import React, { Component } from 'react';
class MyComponent extends Component {
render() {
return (
<div>
<h1>Hello, world!</h1>
</div>
);
}
}
export default MyComponent;
Using the Component: Import and use this component in your main application file, e.g., App.js
.
// src/App.jsx
import React, { Component } from 'react';
import MyComponent from './MyComponent';
class App extends Component {
render() {
return (
<div>
<MyComponent />
</div>
);
}
}
export default App;
Output will be:- Hello, World!
Adding Props to a Class Component
Props are used to pass data from parent to child components.
Modify the Component to Accept Props:
// src/MyComponent.jsx
import React, { Component } from 'react';
class MyComponent extends Component {
render() {
return (
<div>
<h1>Hello, {this.props.name}!</h1>
</div>
);
}
}
export default MyComponent;
Pass Props to the Component:
// src/App.jsx
import React, { Component } from 'react';
import MyComponent from './MyComponent';
class App extends Component {
render() {
return (
<div>
<MyComponent name="World" />
</div>
);
}
}
export default App;
Output will be:- Hello, World!