Closed
Description
openedon Jul 12, 2016
There are almost no situations where you’d want to use findDOMNode()
over callback refs. We want to deprecate it eventually (not right now) because it blocks certain improvements in React in the future.
For now, we think establishing a lint rule against it would be a good start. Here’s a few examples of refactoring findDOMNode()
to better patterns.
findDOMNode(this)
Before:
class MyComponent extends Component {
componentDidMount() {
findDOMNode(this).scrollIntoView();
}
render() {
return <div />
}
}
After:
class MyComponent extends Component {
componentDidMount() {
this.node.scrollIntoView();
}
render() {
return <div ref={node => this.node = node} />
}
}
findDOMNode(stringDOMRef)
Before:
class MyComponent extends Component {
componentDidMount() {
findDOMNode(this.refs.something).scrollIntoView();
}
render() {
return (
<div>
<div ref='something' />
</div>
)
}
}
After:
class MyComponent extends Component {
componentDidMount() {
this.something.scrollIntoView();
}
render() {
return (
<div>
<div ref={node => this.something = node} />
</div>
)
}
}
findDOMNode(childComponentStringRef)
Before:
class Field extends Component {
render() {
return <input type='text' />
}
}
class MyComponent extends Component {
componentDidMount() {
findDOMNode(this.refs.myInput).focus();
}
render() {
return (
<div>
Hello, <Field ref='myInput' />
</div>
)
}
}
After:
class Field extends Component {
render() {
return (
<input type='text' ref={this.props.inputRef} />
)
}
}
class MyComponent extends Component {
componentDidMount() {
this.inputNode.focus();
}
render() {
return (
<div>
Hello, <Field inputRef={node => this.inputNode = node} />
</div>
)
}
}
Other cases?
There might be situations where it’s hard to get rid of findDOMNode()
. This might indicate a problem in the abstraction you chose, but we’d like to hear about them and try to suggest alternative patterns.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment