Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

How to convert functional component to class component in ReactJS ?

  • Last Updated : 24 May, 2021

If we want to convert a function component to a class component then we need to make the following major changes.

  1. Change the function to a class
  2. Add the render method
  3. Convert all function to a method
  4. Add Constructor
  5. Replace hooks with lifecycle methods

Creating React Application:

  • Step 1: Create a React application using the following command:

    npx create-react-app foldername
  • Step 2: After creating your project folder i.e. foldername, move to it using the following command:

    cd foldername

Project Structure: It will look like the following.



Example: Functional Component 

Write down the following code in the App.js file. Here, App is our default component where we have written our code.

App.js




import React, { useState } from 'react';
  
function App(props) {
  
  const [counter, setCounter] = useState(0);
  const myFunction = (e) => {
    alert("The value of counter is " + counter)
    setCounter(counter + 1);
  }
  
  return (
    <div>
        
<p>Hello, {props.name}</p>
  
      <button onClick={myFunction}>Click me!</button>
    </div>
  );
}
  
export default App;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Example: Class Component 

Using the above steps to convert a function component to a class component, we have written the following code in the App.js file. 

App.js




import React, { useState } from 'react';
  
  
class App extends React.Component {
  
  constructor(props) {
    super(props)
    this.state = {
      counter: 0
    }
    this.myFunction = this.myFunction.bind(this);
  }
  
  myFunction(e) {
    alert("The value of counter is " + this.state.counter)
    this.setState({ counter: this.state.counter + 1 })
  }
  
  render() {
    return (
      <div >
        <p>Hello From GFG</p>
  
        <button onClick={this.myFunction}>
         Click me!
        </button>
      </div>
    );
  }
}
  
export default App;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :