RamAlx
RamAlx

Reputation: 7334

Pass a prop in a Hoc function when this prop is inside the component

I know the title is weird but let me explain. I have a component with props:

const MainExperienceComponent = props => (
  <div>
    ....
  </div>
);

and then I need to export it using a wrapper function like this:

export default withWrapper(MainExperienceComponent);

The problem is that I want to pass inside the withWrapper a prop. To be more specific I want this: withWrapper(MainExperienceComponent, prop.id) so as the withWrapper has two args. How to do this?

Upvotes: 3

Views: 2048

Answers (1)

chrisbot
chrisbot

Reputation: 360

You can wrap your MainExperienceComponent within the class you want to use it in (the one that has the props you want to pass) and assign it as an instance variable.

class Container extends Component {
  // inside the constructor:
  constructor(props) {
    super(props)
    this.WrappedComponent = withWrapper(MainExperienceComponent, props.id)
  }

  // or outside the constructor:

  WrappedComponent = withWrapper(MainExperienceComponent, this.props.id)

  render() {
    return (
      // Use <this.WrappedComponent /> here
    )
  }
}

Your HOC would then accept two arguments:

const withWrapper(WrappedComponent, id) => {
  ...
}

This is assuming that the Container component has access to the props you want to pass in. If you're passing the id prop into the MainExperienceComponent component then the HOC would already have access to it.

the caller:

const Wrapped = withWrapper(MainExperienceComponent)
...
<Wrapped id={someId} /> // where does someId come from?

the HOC:

const withWrapper = (WrappedComponent) => {
  class NewComponent extends Component {
    // you have access to `this.props.id`
    render() {
      return <WrappedComponent />
    }
  }

  return NewComponent
}

If this was the case, there would be no need for passing two arguments to the HOC so I'm not sure this answers your question. Let me know if I'm misunderstanding.

Upvotes: 3

Related Questions