From 17233b2a664bbb8c4506aa9343819aaf0680e3e3 Mon Sep 17 00:00:00 2001 From: odm275 Date: Fri, 9 Nov 2018 03:18:02 -0600 Subject: [PATCH] Added a Caveat section with a case (#21299) Added a Caveat sub-section, and covered the refs aren't passed through case with an example. There are still a couple of more caveats. And left a reference to forwarding refs docs. --- .../react/higher-order-components/index.md | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/guide/english/react/higher-order-components/index.md b/guide/english/react/higher-order-components/index.md index 35865d2118..1271c1d841 100644 --- a/guide/english/react/higher-order-components/index.md +++ b/guide/english/react/higher-order-components/index.md @@ -42,7 +42,29 @@ In this case, `enhance` returns an **anonymous class** that extends `React.Compo * Passing its own props to the `WrappedComponent`; and * Injecting an extra prop to the `WrappedComponent`. +### Caveats +Higher-order components come with a few caveats that aren’t immediately obvious if you’re new to React. + +#### Refs Aren't Passed Through +While the convention for higher-order components is to pass through all props to the wrapped component, this does not work for refs. That’s because `ref` is not really a prop — like `key`, it’s handled specially by React. If you add a ref to an element whose component is the result of a HOC, the ref refers to an instance of the outermost container component, not the wrapped component. + +The solution for this problem is to use the React.forwardRef API (introduced with React 16.3) +```jsx +function enhance(WrappedComponent) { + const wrapper = React.createRef((props,ref) => { + return( +
+ +
+ ) + }) +} +``` HOCs are just a pattern that uses the power of React's compositional nature. **They add features to a component**. There are a lot more things you can do with them! ## Other Resources -* [React docs: Higher-Order Components](https://reactjs.org/docs/higher-order-components.html) \ No newline at end of file +* [React docs: Higher-Order Components](https://reactjs.org/docs/higher-order-components.html) +* [React docs: Forwarding Refs](https://reactjs.org/docs/forwarding-refs.html)