Thursday, November 28, 2024
Google search engine
HomeLanguagesReact.js Higher-Order Components

React.js Higher-Order Components

Higher-order components or HOC is the advanced method of reusing the component functionality logic. It simply takes the original component and returns the enhanced component.

Syntax:

const EnhancedComponent = higherOrderComponent(OriginalComponent);

Reason to use Higher-Order component:

  • Easy to handle
  • Get rid of copying the same logic in every component
  • Makes code more readable

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:

Example 1: Let say, we need to reuse the same logic, like passing on the name to every component.

Name.js




import React from 'react'
  
const EnhancedComponent = (OriginalComponent) => {
    class NewComponent extends React.Component {
  
        // Logic here
  
        render() {
            // Pass the callable props to Original component
            return <OriginalComponent name="neveropen"  /> 
        }
    }
    // Returns the new component
    return NewComponent
}
  
export default EnhancedComponent;


App.js




import React from "react";
import "./App.css"
import EnhancedComponent from './Name'
   
class App extends React.Component {
  render() {
    // Call the props from originalComponent
    return <h1>{this.props.name}</h1> 
  }
}
   
// Passed the originalcomponent 
export default EnhancedComponent(App);


Output: Here, we pass the name as a prop with the value for calling out from different components.

Example 2: In this example let’s implement some logic. Let’s make a counter app. In HighOrder.js, we pass the handleclick and show props for calling the functionality of the component.

Project Structure:

HighOrder.js




import React from 'react'
  
const EnhancedComponent = (OriginalComponent) => {
    class NewComponent extends React.Component {
  
        constructor(props) {
            super(props);
            // Set initial count to be 0
            this.state = { count: 0 }; 
        }
  
        handleClick = () => {
            // Incrementing the count
            this.setState({ count: this.state.count + 1 }); 
        }
  
        render() {
  
            // passed a handleclick and count in the originalComponent
            // as a props for calling and adding the functionality
            return <OriginalComponent
                handleclick={this.handleClick} 
                show={this.state.count} /> 
        }
    }
    // Returns the new component
    return NewComponent 
}
// Export main Component
export default EnhancedComponent 


App.js




import React from 'react'
import "./App.css"
// importing HighOrder file
import EnhancedComponent from './HighOrder' 
  
class App extends React.Component {
  render() {
    // Destructuring the props
    const { show, handleclick } = this.props
  
    // Calling out the props
    return <button onClick={handleclick}>{show}
    </button> 
  }
}
  
  
export default EnhancedComponent(App);


Output:

Reference:https://reactjs.org/docs/higher-order-components.html

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments