How to convert functional component to class component in ReactJS ?
If we want to convert a function component to a class component then we need to make the following major changes.
- Change the function to a class
- Add the render method
- Convert all function to a method
- Add Constructor
- 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:
Please Login to comment...