I try to use refs as least often as possible, but it seems there's no way around it for calling native dom methods (focus(), reset(), blur() etc) so I'm okay with that. Except, that I'd like to use the new stateless component functions for such basic things as form inputs, which as it stands, these stateless components do not allow refs pointing to them (they will return null). I understand that I can add a regular React class component wrapper around the stateless component to allow for ReactDOM.findDOMNode(ref) to work correctly, but what's the point of having the stateless function if it always has to be wrapped? Am I missing something?
5 Answers
Here's a solution that I came up with that doesn't require wrapping the stateless component in a class. Instead it involves the parent passing a function to the stateless component as a prop that is used as the callback function for the ref on the DOM element.
First set a method on the stateful parent that will be used as a callback to the ref, and another method for doing the action on the DOM element (in this case focusing after a key press). Then send the method to the stateless child as a prop.
// note: Facebook now recommends using native js classes instead of React.createClass().
// note 2: You may need Babel to transpile some of ES6 syntax in use here.
const StatefulParent = React.createClass({
getInitialState() {
return {
// doesn't matter for this example
}
},
componentDidMount() {
document.addEventListener('keyup', this.keyUp, false)
},
keyUp() {
// calls the DOM focus method on the input when the 'tab' key is pressed
if (e.keyCode === 9) this._input.focus()
},
inputSetter(ref) {
this._input = ref
},
render() {
<StatelessTextInput {...this.state} refCallback={this.inputSetter} />
}
})
The stateless component assumes a method will be passed to it from the parent called refCallback. This prop can be passed down any number of component generations to reach the DOM element.
const StatelessTextInput = ({refCallback, ...props}) => (
<input {...props} ref={refCallback} />
)
Just wrap your stateless component with class component (es6) an attach ref. It's written in the official docs
-
5Sure but what's the point of making a stateless function if you have to wrap it in a class? Might as well just use a class to begin with in that case.– BrimbyCommented Jul 29, 2016 at 18:49
-
Stateless functions is like pure functions and uses for presentational purpose. Just grab the props and render view without any sides effects. So If your component needs some non-trivial behave it's time to extract class component.– andreoCommented Jul 29, 2016 at 19:06
The cleanest solution I found is by setting a local variable and then assigning ref to it. Then this can be accessed and focused when needed:
const Item = () => {
let input;
const click = () => {
if (input){
input.focus();
}
};
return (
<div>
<a href="#" onClick={click}>clickMe</a>
<input ref={e => (input = e)}/>
</div>
);
};
-
Yes that is easy if you are reffing an html element within its immediate parent. But if there is another level of separation (a grandparent needing the ref of a grandchild) and the component in the middle (the parent) is a stateless function... that's the scenario I put forth.– BrimbyCommented Dec 2, 2016 at 6:16
yes, just remember it during rendering and carry it out, and focus on it after rendered:
function Main(props) {
<input ref={e => { props.elems.input = e; }}
}
const elems = {};
ReactDOM.render(Main({ elems }), containerElement);
elems.input.focus();
Just had this problem too with a stateless component. In at least React v16, you can get a reference to the element like this:
<Button
onClick={(el) => {
el.target.blur();
}}>
Button Text
</Button>