Professional Documents
Culture Documents
Components in React
Valentine Gatwiri
First, you'll de�ne the HOC function. This is a function that takes a component as
input and returns a new component with additional functionality.
Then you de�ne the new component. This is a class component that wraps the
WrappedComponent and adds additional functionality.
class NewComponent extends React.Component {
// ...
render() {
// ...
}
}
Next, you pass props to the WrappedComponent . In the render() method of the
NewComponent , pass all the props (including the additional props added by the HOC)
to the WrappedComponent .
render() {
return <WrappedComponent {...this.props} additionalProp={additionalProp} />
}
Finally, return the new component. The HOC function should return the
NewComponent so it can be used in the application.
// ...
}
}
return NewComponent;
}
Instead of duplicating the authentication logic in each component or route, you can
create an HOC called withAuth that checks if the user is authenticated and
redirects them to the login page if not. Then, you can wrap the speci�c components
or routes that need authentication with this HOC, reducing duplication and
enforcing consistent authentication behavior.
Logging
Imagine you want to log some data every time a speci�c set of components mount
or update. Rather than adding the logging logic to each component, you can create
an HOC called withLogger that handles the logging functionality.
By wrapping the relevant components with withLogger , you can achieve consistent
logging across those components.
This way, the wrapped component can easily access and apply the appropriate
styles based on the provided theme.
componentDidMount() {
setTimeout(() => {
this.setState({ isLoading: false });
}, 2000);
}
render() {
return (
<WrappedComponent
{...this.props}
loading={this.state.isLoading}
/>
);
}
}
return WithLoading;
};
ReactDOM.render(
<MyComponentWithLoading />,
document.getElementById("root")
);
The WithLoading component sets the isLoading state to true initially, then after 2
seconds, sets it to false. The WrappedComponent is rendered with the loading prop
set to this.state.isLoading .
Assuming you already have Node.js and npm installed on your system, open a
terminal window and run the following commands:
Create the withLogger HOC in the src folder, create a new �le named
withLogger.js . Copy the following code into the �le:
useEffect(() => {
// Log data on component update
console.log(`Component ${WrappedComponent.name} updated.`);
});
return (
<div>
<h1>Todo List</h1>
<TodoForm newTodo={newTodo} setNewTodo={setNewTodo} addTodo={addTodo} />
<ul>
{todos.map((todo, index) => (
<TodoItem key={index} todo={todo} onComplete={() => completeTodo(index
))}
</ul>
</div>
);
};
In the above code we have implemented the TodoList component and used the
withLogger HOC to add logging functionality to it. The TodoList component
manages the state for a list of todos and provides functions to add and complete
todos.
The above is a simple functional component that renders a single todo item with its
corresponding "Complete" button.
This TodoItem component is responsible for displaying individual todo items and
allows the user to complete them by clicking the "Complete" button. It is a simple
and essential part of the Todo List app, and when used in conjunction with the
TodoList component, it should provide a complete and functional Todo List
experience.
This is a functional component responsible for rendering the input �eld and "Add
Todo" button, allowing users to add new todos to the list.
With this TodoForm component, users can input a new todo item in the input �eld
and click the "Add Todo" button to add it to the list managed by the TodoList
component.
Update the App component to use MyComponent
Open the App.js �le in the src folder and replace its content with the following
code:
function App() {
return (
<div>
<TodoList />
</div>
);
}
Save all the �les and go back to the terminal. Make sure you are still in the project
root folder ( hoc-example ). Now, start the development server by running the
following command:
npm start
Additionally, each time you add or complete a task, the app will log the events in the
browser console using the withLogger HOC. For example, the console will show:
That's it! You have now implemented a real-world example of using the withLogger
Higher-Order Component in a React project. Here is the full GitHub code