Balls McHenry Balls McHenry - 5 days ago 4
React JSX Question

Is it possible to call dom element methods like focus() without using a ref? (Stateless Component Functions)

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. 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?

Answer

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 focus()). Then send the method to the stateless child as a prop.

var Parent = React.createClass({
  focus() {
    if (!isNullOrUndefined(this.input)) this.input.focus()
  },
  returnInputRef(ref) {
    this.input = ref
  },
  render(){
    <div>
      <Label />
      <TextInput returnRef={this.returnInputRef} />
    </div> 
  }
})

The stateless component assumes a method will be passed to it from the parent called returnRef. It is defaulted to a function that returns undefined in case that doesn't happen.

export var TextInput = (props) => <input {...props} type='text' 
    ref={props.returnRef} />
TextInput.defaultProps = {returnRef: _.noop}
Comments