Refs over findDOMNode()

Use callback refs over findDOMNode()

Note:
React also supports using a string (instead of a callback) as a ref prop on any component, although this approach is mostly legacy at this point.

findDOMNode(this)
Before:
  1. class MyComponent extends Component {
  2. componentDidMount() {
  3. findDOMNode(this).scrollIntoView();
  4. }
  5. render() {
  6. return <div />
  7. }
  8. }
After
  1. class MyComponent extends Component {
  2. componentDidMount() {
  3. this.node.scrollIntoView();
  4. }
  5. render() {
  6. return <div ref={node => this.node = node}/>
  7. }
  8. }
findDOMNode(stringDOMRef)
Before
  1. class MyComponent extends Component {
  2. componentDidMount() {
  3. findDOMNode(this.refs.something).scrollIntoView();
  4. }
  5. render() {
  6. return (
  7. <div>
  8. <div ref='something'/>
  9. </div>
  10. )
  11. }
  12. }
After
  1. class MyComponent extends Component {
  2. componentDidMount() {
  3. this.something.scrollIntoView();
  4. }
  5. render() {
  6. return (
  7. <div>
  8. <div ref={node => this.something = node}/>
  9. </div>
  10. )
  11. }
  12. }
findDOMNode(childComponentStringRef)
Before:
  1. class Field extends Component {
  2. render() {
  3. return <input type='text'/>
  4. }
  5. }
  6. class MyComponent extends Component {
  7. componentDidMount() {
  8. findDOMNode(this.refs.myInput).focus();
  9. }
  10. render() {
  11. return (
  12. <div>
  13. Hello,
  14. <Field ref='myInput'/>
  15. </div>
  16. )
  17. }
  18. }
After
  1. class Field extends Component {
  2. render() {
  3. return (
  4. <input type='text' ref={this.props.inputRef}/>
  5. )
  6. }
  7. }
  8. class MyComponent extends Component {
  9. componentDidMount() {
  10. this.inputNode.focus();
  11. }
  12. render() {
  13. return (
  14. <div>
  15. Hello,
  16. <Field inputRef={node => this.inputNode = node}/>
  17. </div>
  18. )
  19. }
  20. }