A
A
Alexey Kostyukhin2020-02-05 13:44:10
React
Alexey Kostyukhin, 2020-02-05 13:44:10

How to write a HOC component in ReactJS?

Learning React patterns, going through the topic with HOC (Higher Order Components).
There is a "Teacher" code that looks like this:

spoiler
const with-BookStore-Service = () => (wraped) => {
  return (props) {
    return (
      <Consumer>
        {
          (value) => {
            return (
              <Wraped {...props}
            )
          }
        }
      <Consumer>
    )
  }


Why are we passing our "main" component to a second function
with-BookStore-Service = () => (wrapped) =>


Can be made shorter:
spoiler

const withTest = (wraped) => (props) => {
 return (
      <Consumer>
        {
          (value) => {
            return (
              <Wraped {...props}>
            )
          }
        }
      <Consumer>
)
}


Why is my code worse?
Everything works and the components turn around well, my HOC component does its job with a bang.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2020-02-05
@aleksey4uk

() => (wraped)
It will make sense if there are some parameters in the first brackets.
That is, you can make a function that will be somehow configured, which can be called by passing wraped.
For example

const withBookStoreService = (consProps) => (wraped) => {
  return (props) {
    return (
      <Consumer ...consProps>
        {
          (value) => {
            return (
              <Wraped {...props}
            )
          }
        }
      <Consumer>
    )
  }

Then you can do
const hoc1 = withBookStoreService(props)
const hoc2 = withBookStoreService(otherProps)

const wrappedInHoc1 = hoc1(component)
const wrappedInHoc2 = hoc2(component)

Most likely in the original it was so, then they simply simplified it to the point of losing meaning. In the form you presented, this is of course an unnecessary construction.
you can also write () =>() =>() => (wrapper)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question