fynmnx
fynmnx

Reputation: 611

How to get HOC in react to override props?

My props on an HOC do not seem to be overriding. I feel as though it might be the notation I'm using. Here is what I have right now.

export const HOCComponent = ({ someProp }) => (
  <ContainerComponent
    propOne={someValueOne}
    propTwo={someValueTwo}
    propThree={someValueThree)
  />
);

export const wrapperComponent = props =>(
  <HOCComponent {...props} propThree={someValueFour}/>
);

someValueFour does not seem to override someValueThree. Any suggestions would be super helpful! Thank you.

Upvotes: 2

Views: 2721

Answers (2)

Drew Reese
Drew Reese

Reputation: 202618

Swap the order of the passed props such that anything you pass later overrides anything passed previously.

export const wrapperComponent = props =>(
  <HOCComponent propThree={someValueFour} {...props} />
);

The HOCComponent wrapper component needs to also pass along all props to the component it's wrapping.

export const HOCComponent = (props) => (
  <ContainerComponent
    propOne={someValueOne}
    propTwo={someValueTwo}
    propThree={someValueThree}
    {...props}
  />
);

Just a minor point about terminology, nothing in your code snippet is a Higher Order Component. HOCs consume a React component and return a new React Component.

An Example:

const withMyHOC = WrappedComponent => props => {
  // any HOC logic
  return (
    <Wrapper
      // <-- any wrapper props
    >
      <WrappedComponent
        {...props} // <-- pass props through
        // <-- override any props
      />
    </Wrapper>
  );
};

usage:

export default withMyHOC(SomeComponent);

Upvotes: 5

Viet
Viet

Reputation: 12777

I saw you don't pass props from HOCComponent to ContainerComponent so propThree is not override. You need to pass someProp to ContainerComponent:

<ContainerComponent propOne propTwo propThree {...someProp} />

Upvotes: 0

Related Questions