From e7914b5487d0d9e5ef8a46ba1864c001faacd291 Mon Sep 17 00:00:00 2001 From: Dan Abramov Date: Fri, 5 Jan 2018 18:07:36 +0000 Subject: [PATCH] Add more info about refs --- content/warnings/refs-must-have-owner.md | 36 ++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/content/warnings/refs-must-have-owner.md b/content/warnings/refs-must-have-owner.md index 2a03a57b..74b6ea1c 100644 --- a/content/warnings/refs-must-have-owner.md +++ b/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. -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 have multiple (conflicting) copies of React loaded (eg. due to a misconfigured npm dependency) +## Refs on Functional Components -## Invalid Refs +If `` 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! + +``` + +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(, 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 = 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