How To Create Class Component In React JS

04-Apr-2023

.

Admin

How To Create Class Component In React JS

Hi Friends,

In this tutorial we are learing how to create class component in react js. also react js is develop on component base.

What Is Component ?


Component means specific part of code which is we can reuse in our project. example header,footer etc...

Why Use Component ?

Beause of we can not write same code second time. we are use our code reuse in our application.

Types of Component ?

In React js two types of Component

1. Functional Component

2. Class Component

Create Class Component

In react js class component is very powerfull and usefull. and also this component call statefull component. In "src" folder you have to create ".js" extension file. then first you have to import "React" in every component like "import React from 'react'". then you have to create class and extend Component class like "React.Component". next you have to create render method in this method you have to return HTML.

Now you have to use this component then you have to export this component using "export default".

This is Home Component Example

import React from 'react'

class Home extends React.Component{

render(){

return(

<div>

<h1> This is Home Component. </h1>

</div>

)

}

}

export default Home;

How To Use Class Component ?

Now we have to use this component in App.js. First we have to import Home Component in this file. Then simple you can use like this "".

import React from 'react';

import logo from './logo.svg';

import './App.css';

import Home from './Home';

function App() {

return (

<div className="App">

<header className="App-header">

<img src={logo} className="App-logo" alt="logo" />

<p> Edit < code>src/App.js </code> and save to reload. </p>

<a

className="App-link"

href="https://reactjs.org"

target="_blank"

rel="noopener noreferrer"

>

Learn React

</a>

<Home/>

</header>

</div>

);

}

export default App;

Now you have to run reactjs app or project then you have to run following command.

npm start

I hope it can help you...

#React.js