DEV Community

Himanshu Gupta
Himanshu Gupta

Posted on

React Higher Order Component Function Component Tutorial

In this tutorial, we will learn and find out about higher-order components and how to create and use higher-order components in React.

In this React higher-order component example, we will create a higher-order component from existing React components.

A higher-order component (HOC) is an advanced React technique or a function used for reusing the component’s core logic. A hoc pattern is a simple pattern in which the Hoc component takes a component as a parameter and returns a new or enhanced component.

Hoc allows you to create a new component without rewriting the main code repeatedly.

In this guide, we will create two search filters using the mock json placeholder api. Two components will have a search filter that works after making the api request. Both the components share the common logic only the apis are diffrent. We are going to handle this scenario through the Hoc pattern.

By the end of this tutorial, you will comprehend the basics of higher-order components and profoundly understand how to build and use them.

How to Create and Use Higher Order Component in React Js with Functional Component

Step 1: Build React App
Step 2: Create Component Files
Step 3: Create Higher Order Component
Step 4: Make Users List with HOC
Step 5: Create Todo List with HOC
Step 6: View App in Browser

Build React App
Before you start installing the react app, ensure that you have the create-react-app tool installed in your system:

npm install create-react-app --global
Bash

Copy

Execute the suggested command and let the React application install swiftly:

npx create-react-app react-hoc-example
Bash

Copy

Further, you have to move into the project’s root:

cd react-hoc-example
Create Component Files
Now, make sure to create the files that will hold the users, todo lists code also create the hoc component file.

Create the TodoList.js file in the src/ folder:

import React from 'react'
function TodoList() {
  return (
    <div>TodoList</div>
  )
}
export default TodoList
Formulate the UserList.js file in the src/ folder:

import React from 'react'
function TodoList() {
  return (
    <div>TodoList</div>
  )
}
export default TodoList
Create Higher Order Component
Enter fullscreen mode Exit fullscreen mode

The higher-order component takes a component as an argument and returns a new enhanced component. As you can see, we passed the WrappedComponent and entity parameters.

The wrapped component will be the new enhanced component, whereas the entity is the value that we will pass from the child components. It will help us lift the state without even touching the core functionality of the Hoc.

You need to make the Hoc.js file inside the src/ folder and insert the following code into the file:

import React from 'react'
const Hoc = (WrappedComponent, entity) => {
  return class extends React.Component {
    state = {
      data: [],
      term: '',
    }
    componentDidMount() {
      const fetchData = async () => {
        const res = await fetch(
          `https://jsonplaceholder.typicode.com/${entity}`,
        )
        const json = await res.json()
        this.setState({ ...this.state, data: json })
      }
      fetchData()
    }
    render() {
      let { term, data } = this.state
      let filteredData = data.slice(0, 10).filter((d) => {
        if (entity === 'users') {
          const { name } = d
          return name.indexOf(term) >= 0
        }
        if (entity === 'todos') {
          const { title } = d
          return title.indexOf(term) >= 0
        }
      })
      return (
        <div>
          <h2>Users List</h2>
          <div>
            <input
              type="text"
              value={term}
              onChange={(e) =>
                this.setState({ ...this.state, term: e.target.value })
              }
            />
          </div>
          <WrappedComponent data={filteredData}></WrappedComponent>
        </div>
      )
    }
  }
}
export default Hoc
Enter fullscreen mode Exit fullscreen mode

Make Users List with HOC
In the UserList component, import the Hoc component, and pass the data props that we defined in the wrapped component in the Hoc file.

After defining the logic, pass the UserList component in the Hoc component along with ‘users’ property. The users’ property is the entity property that we will receive in the Hoc component.

Open the src/UserList.js file and insert the suggested code into the file:

import React from 'react'
import Hoc from './Hoc'
const UserList = ({ data }) => {
  let usersList = data.map((item) => {
    return <div key={item.id}>{item.name}</div>
  })
  return <div className="container">{usersList}</div>
}
const SearchUsers = Hoc(UserList, 'users')
export default SearchUsers
Enter fullscreen mode Exit fullscreen mode

Create Todo List with HOC
Head over to the src/TodoList.js file and place the provided code within the file:

import React from 'react'
import Hoc from './Hoc'
const TodoList = ({ data }) => {
  let todos = data.map((todo) => {
    return <div key={todo.userId}>{todo.title}</div>
  })
  return <div className="container">{todos}</div>
}
const TodosItems = Hoc(TodoList, 'todos')
export default TodosItems
Enter fullscreen mode Exit fullscreen mode

For App in Browser
Start react server:npm start
let todos = data.map((todo) => {
return

{todo.title}
})
return {todos}
}
const TodosItems = Hoc(TodoList, 'todos')
export default TodosItems

Enter fullscreen mode Exit fullscreen mode

Top comments (0)