If you want to access refs of child component in ReactJS? Accessing the refs of a child breaks encapsulation since refs are not considered part of a component’s API. Instead you should expose a function on Inner that can be called by a parent component, calling it focus might make sense.
Also, focus the element in componentDidUpdate to ensure rendering is complete:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | { div, input } = React.DOM Outer = React.createClass render: -> div { id: 'myApp' }, Inner({ref: 'inner'}) componentDidUpdate: (prevProps, prevState) -> # Focus if `visible` went from false to true if (@state.visible && !prevState.visible) @refs.inner.focus() hide: -> @setState { visible: no } show: -> @setState { visible: yes } toggle: -> if @state.visible @hide() else @show() Inner = React.createClass focus: -> @refs.myInput.getDOMNode().focus() render: -> input { id: 'myInput', ref: 'myInput' } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.