If you find yourself needing to incorporate jQuery into your React code, I suggest using the ref
utility to manage DOM events instead of directly relying on jQuery.
When utilizing the on()
method with multiple events, consider passing an object with multiple methods rather than nesting them.
Instead of using the alert()
method, opt for console.log()
for retrieving data or DOM elements to avoid errors.
I've also left a comment in your regex section to verify its functionality - it seems to be returning null while the rest of the code is operational.
Check out the CodeSandbox demo here.
PS: The recommended React approach follows below:
import React, { Component } from "react";
import "./styles.css";
import $ from "jquery";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {};
this.myRef = React.createRef();
}
componentDidMount() {
$(this.myRef.current).on({
mousedown: function(evt) {
console.log(
$(this).attr("class")
// .match(/\bsizes[^\s]+\b/)
);
},
mouseup: function(evt) {
console.log(
$(this).attr("class")
// .match(/\bsizes[^\s]+\b/)
);
},
mousemove: function(evt) {
console.log(
$(this).attr("class")
// .match(/\bsizes[^\s]+\b/)
);
}
});
}
render() {
return <div className="MainContainer sizes" ref={this.myRef} />;
}
}
The React Way
As suggested earlier, try to stick with pure React for handling DOM operations. Here's the React code implementation:
Note: While looping through events can be achieved programmatically, manually repeating events may reduce complexity. I utilized find()
to iterate through values of DOMTokenList
and checked against the regex pattern. This line has been commented out to skip the regex check response.
View this version on Codesandbox.
import React, { Component } from "react";
import "./styles.css";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {};
this.myRef = React.createRef();
}
componentDidMount() {
this.eventHandler();
}
eventHandlerCallback = e => {
console.log(
Object.values(e.target.classList)
// .find(item => item.match(/\bsizes[^\s]+\b/))
);
};
eventHandler = () => {
const events = ["mousedown", "mouseup", "mousemove"];
events.map(e =>
this.myRef.current.addEventListener(e, this.eventHandlerCallback)
);
};
render() {
return <div className="MainContainer sizes" ref={this.myRef} />;
}
}