How To Create Class Component In React JS

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Hello all , Today now in this tutorial i will show you how to create class component by using react js. Also we know react js is develop based on component base.

What Is Component ?

We know that component means specific part of code which is we can reuse in our project. For example header,footer etc…

Why Use Component ?

We are using component because of we can not want to write same code second time. That’s why we are use our code reuse in our application.

Types of Component ?

We are know that in React js two types of Component

1. Functional Component

2. Class Component

Create Class Component

We are know in react js class component is very powerful and also more useful. And also in this component is call state full component. So in “src” folder you need to create “.js” extension file. And then first we need to import “React” in every component as like “import React from ‘react'”. So then we need to create class and extend Component class as like “React.Component”.Now next we need to create render method in this method we have to return HTML.

Now we need to use this component then you can export this component by 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 ?

So now we need to use this component in App.js. At first we need to import Home Component in this file. So then simple we 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 we need to run reactjs app or project then we need to run following command.

npm start

Read Also : Laravel 8 Eloquent Global Scope Tutorial Example

I hope it will help you. Also you can follow us on Facebook

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →