top of page
Logo der Online Agentur mdwp

Higher-Order Components (HOC)

Higher-Order Components (HOC) is a React JS term that refers to an advanced method for reusing component logic. Rather than being a part of the React API, they are a pattern that stems from React’s compositional nature.

In simple terms, a higher-order component is essentially a function that accepts a React component and returns a new React component. It takes a component, transforms it in some way, and then returns the new, transformed component.

The higher-order component (HOC) pattern is similar to a higher-order function, which is a function that accepts a function as an argument or returns a new function. HOCs are used for operations that can be defined in multiple components such as rendering logic, state manipulation and event handling.

Here's a simple example of an HOC:

```jsx
// This is a basic higher-order component (HOC) that will just add some props

function withExtraProps(WrappedComponent, extraProps) {
return function(props) {
return <wrappedcomponent {...props}="" {...extraprops}="">
}
}

// Usage Example
function MyComponent({name, age}) {
return <div>{name} is {age} years old</div>
}

const MyComponentWithExtraProps = withExtraProps(MyComponent, {age: 20});

// This will render "<div>John is 20 years old</div>"
ReactDOM.render(<mycomponentwithextraprops name="John">, document.getElementById('root'));
```

In this case, `withExtraProps` is a higher-order component. It is a function that takes a component and some extra props. It returns a new component that renders the original component with its original props and the extra props injected.</mycomponentwithextraprops></wrappedcomponent>

bottom of page