jqueryreactjsreact-refjquery-mask

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


Solution

  • 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);
      }
    }