Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 250
Alexey Nikonov Avatar asked Aug 14 '26 00:08

Alexey Nikonov


1 Answers

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.

like image 168
palaѕн Avatar answered Aug 15 '26 19:08

palaѕн



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!