Oleksiï Nikonov
Oleksiï Nikonov

Reputation: 5598

Use react ref as selector for jquery

How to use React Ref together with jQuery lib without specified id to the input?

import $ from 'jquery';
import 'jquery.mask.js';

class PhoneComponent extends React.Component {
  ref = React.createRef();

  state = {value: ''};

  componentDidMount() {
    this.renderMask();
  }

  render() {
    return (
      <input ref={this.ref} type="text"/>
    )
  }


  renderMask() {
    const { value } = this.state;
    const options = {
      onKeyPress: (cep, e) => this.ref.current.value = cep
    };
    $(***???***).val(value);
    $(***???***).mask('+38(###)###-##-##', options);
  }

I would like to share experience as far as i found out it

Upvotes: 3

Views: 5619

Answers (2)

Oleksi&#239; Nikonov
Oleksi&#239; Nikonov

Reputation: 5598

that is so simple but not clear in docs.

The ref.current refers to used DOM element and allows to access it for jQuery

class YourComponent extends React.Component{
  this.ref = React.createRef();
  ...
  doSomething = () => {
    $(this.ref.current).val(value);
    $(this.ref.current).mask(mask, options);
  }
}

Upvotes: 2

palaѕн
palaѕн

Reputation: 73966

As mentioned in react docs, titled "Refs and the DOM"

const node = this.myRef.current;

When the ref attribute is used on an HTML element, the ref created in the constructor with React.createRef() receives the underlying DOM element as its current property.

Also, as mentioned in jQuery docs, titled "How do I select elements when I already have a DOM element?"

If you have a variable containing a DOM element, and want to select elements related to that DOM element, simply wrap it in a jQuery object.

var myDomElement = document.getElementById( "foo" ); // A plain DOM element. 
$( myDomElement ).find( "a" ); // Finds all anchors inside the DOM element.

Combining these two descriptions we can say that, to use react ref as a selector for jquery we can simply do:

$( this.ref.current ).val(value);
$( this.ref.current ).mask('+38(###)###-##-##', options);

where, this.ref.current is a plain DOM element.

Upvotes: 2

Related Questions