4

I sometimes find it useful to use React's Refs in order to change the state of the DOM as for example to focus an input field after rendering a component. Does Reagent or Om implement this or if not what is the idiomatic way to do this in those libraries?

EDIT (after the discussion below).

The use of this.getDOMNode in componentDidMount is not a generic solution to this problem. It only allows access to the physical DOM element after a component is mounted. Sometimes consistent access to an element is required after every call to render - as for example for triggering events. The way to do that is through Refs.

Aliaksandr Sushkevich
  • 7,264
  • 6
  • 29
  • 36
kliron
  • 3,895
  • 3
  • 28
  • 43
  • You can do it in `componentDidMount` method, but it is not recommended. – Aleš Roubíček Nov 12 '14 at 20:26
  • "At this point in the lifecycle, the component has a DOM representation which you can access via this.getDOMNode()" – Aleš Roubíček Nov 13 '14 at 12:52
  • "Remember, what you return from render() is not your actual rendered children instances. What you return from render() is merely a description of the children instances in your component's sub-hierarchy at a particular moment in time." – kliron Nov 13 '14 at 13:19
  • "React supports a very special property that you can attach to any component that is output from render(). This special property allows you to refer to the corresponding backing instance of anything returned from render(). It is always guaranteed to be the proper instance, at any point in time." – kliron Nov 13 '14 at 13:19
  • That very special property is a Ref. Did you actually read the page? – kliron Nov 13 '14 at 13:20
  • I did. :) I'm using `componentDidMount` to access real DOM elements without any trouble (concretely rendering of JointJS graphs). This is the point in React lifecycle, where you should do it. – Aleš Roubíček Nov 13 '14 at 16:09
  • Your solution "works" only when mounting a component. Try doing a focus on an input field for example every time you re-render a component. This is never going to work. This is exactly the use case of Refs. – kliron Nov 13 '14 at 20:27

1 Answers1

4

I found the answer from the author of Reagent here if anyone cares to look. It turns out refs cannot be directly supported because of the way Reagent does its rendering. The proposed solution is to wrap the portion of a component that needs to be referenced in another component and use component-did-mount in the wrapper.

kliron
  • 3,895
  • 3
  • 28
  • 43