kentcdodds / advanced-react-patterns-v2

Created with CodeSandbox
https://codesandbox.io/s/github/kentcdodds/advanced-react-patterns-v2
1.51k stars 567 forks source link

HOC Exercise fails even though my code matches the video #50

Closed EddyVinck closed 6 years ago

EddyVinck commented 6 years ago

I stumbled upon something. My code for the HOC matches the code in the video, but the tests still fail. The code in /exercises-final is different and passes the tests. Why? Did the hoistNonReactStatics API change?

My code:

function withToggle(Component) {
  const Wrapper = React.forwardRef((props, ref) => {
    return (
      <Toggle.Consumer>
        {(toggleUtils) => (
          <Component {...props} toggle={toggleUtils} ref={ref} />
        )}
      </Toggle.Consumer>
    );
  });
  Wrapper.displayName = `withToggle(${Component.displayName ||
    Component.name})`;
  hoistNonReactStatics(Wrapper, Component);

  return Wrapper;
}

The code above is the exact same code as in the course (FEM) but the tests are still failing. What's going on?

The code in /exercises-final

function withToggle(Component) {
  function Wrapper(props, ref) {
    return (
      <Toggle.Consumer>
        {(toggleContext) => (
          <Component {...props} toggle={toggleContext} ref={ref} />
        )}
      </Toggle.Consumer>
    );
  }
  Wrapper.displayName = `withToggle(${Component.displayName ||
    Component.name})`;
  return hoistNonReactStatics(React.forwardRef(Wrapper), Component);
}

This is what the tests are saying:

image

gpetrioli commented 6 years ago

@EddyVinck , it is not the exact same code.

In the working code the displayName is applied to the Wrapper element before being passed to React.forwardRef while in your code you apply the displayName to the returned object so it is not associated with the actual component that gets rendered. You could log the Wrapper variable in both cases and you will see the difference.

EddyVinck commented 6 years ago

Thank you for looking into this. I will post an update when I work on this course again, which is probably this weekend or earlier.

kentcdodds commented 6 years ago

Thanks @gpetrioli!