Browse Source

Add more info about refs

main
Dan Abramov 7 years ago
committed by GitHub
parent
commit
e7914b5487
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 36
      content/warnings/refs-must-have-owner.md

36
content/warnings/refs-must-have-owner.md

@ -16,15 +16,45 @@ You are probably here because you got one of the following error messages:
> >
> addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded. > addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded.
This usually means one of two things: This usually means one of three things:
- You are trying to add a `ref` to a functional component.
- You are trying to add a `ref` to an element that is being created outside of a component's render() function. - You are trying to add a `ref` to an element that is being created outside of a component's render() function.
- You have multiple (conflicting) copies of React loaded (eg. due to a misconfigured npm dependency) - You have multiple (conflicting) copies of React loaded (eg. due to a misconfigured npm dependency)
## Refs on Functional Components
## Invalid Refs If `<Foo>` is a functional component, you can't add a ref to it:
Only a ReactOwner can have refs. This usually means that you're trying to add a ref to a component that doesn't have an owner (that is, was not created inside of another component's `render` method). Try rendering this component inside of a new top-level component which will hold the ref. ```js
// Doesn't work if Foo is a function!
<Foo ref={foo} />
```
If you need to add a ref to a component, convert it to a class first, or consider not using refs as they are [rarely necessary](/docs/refs-and-the-dom.html#when-to-use-refs).
## Strings Refs Outside the Render Method
This usually means that you're trying to add a ref to a component that doesn't have an owner (that is, was not created inside of another component's `render` method). For example, this won't work:
```js
// Doesn't work!
ReactDOM.render(<App ref="app" />, el);
```
Try rendering this component inside of a new top-level component which will hold the ref. Alternatively, you may use a callback ref:
```js
let app;
ReactDOM.render(
<App ref={inst => {
app = inst;
}} />,
el
);
```
Consider if you [really need a ref](/docs/refs-and-the-dom.html#when-to-use-refs) before using this approach.
## Multiple copies of React ## Multiple copies of React

Loading…
Cancel
Save