Using JQuery to retrieve part of a className results in a null value being returned

I am facing an issue with a piece of code in codesandbox where it returns null when I attempt to retrieve part of the className from a div using JQuery. How can I troubleshoot this and make it work?

Check out the Codesandbox Example

import React, { Component } from "react";
import "./styles.css";
import $ from "jquery";

export default class App extends Component {
  componentDidMount() {
    $(".MainContainer").on("mousedown", function(evt) {
      $(".MainContainer").on("mouseup mousemove", function handler(evt) {
        alert(
          $(this)
            .attr("class")
            .match(/\bsizes[^\s]+\b/)
        );
      });
    });
  }

  constructor(props) {
    super(props);

    this.state = {};
  }

  render() {
    return <div className="MainContainer sizes" />;
  }
}

The CSS class:

.MainContainer {
  background: #282c34;
  position: relative;
  display: flex;
  min-height: 100vh;
}

Answer №1

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} />;
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Align the headers of columns to the right in the AgGrid widget

Is there a way to align the column headers to the right in AgGrid without having to implement a custom header component? It seems like a lot of work for something that should be simple. You can see an example here: https://stackblitz.com/edit/angular-ag-g ...

What is the best way to use jQuery to attach functions to every input element?

Imagine you have a set of HTML markup and CSS like this: #CSS .inputhelp_text { background: #000; color: #fff; } .nodisplay { display: none; } <input class="inputhelp" id="firstname" /><span class="inputhelp_text nodisplay" id="help_firstname"& ...

Most effective method for transferring data to linked selection fields across multiple components

I apologize for the recent influx of questions, but our volunteer mission is scheduled for December and I have a lot to accomplish. These initial inquiries will assist me in completing the remaining tasks! At this point, I am seeking the most effective me ...

Is it achievable to create shadows that do not overlap?

When you hover your mouse over the pill-shaped object, it should smoothly move over the circle as desired. However, the shadow of the circle still remains visible creating an unwanted effect. I am looking for a solution where the shadows do not overlap but ...

What are some methods for transferring the state variable's value from one component to another in React?

I have the following scenario in my code: there is a Form.js component that interacts with an API, stores the response in the walletAssets state variable, and now I want to create a separate Display.js component to present this data. How can I pass the v ...

Update HTML element using Jquery periodically

I have a PHP script that updates me with the upcoming bus departure time. Currently, I am using jQuery to refresh this information in a div every minute. However, since I know when the data will change (after the bus arrives), I want the div to refresh at ...

Unable to Access ReactJS Nested Property in JSON Data

While attempting to access a nested property in my JSON file loaded into the state, I encountered an issue. Despite confirming the existence of the property within the object through logging, when trying to navigate a level deeper using dot-notation, an er ...

Guide to quickly redirecting all 404 links to the homepage on a simple HTML website

Is there a way to automatically redirect clients to the homepage if they click on a broken link in a basic HTML website, instead of displaying a custom 404 page? UPDATE: My website consists of only 5 plain HTML pages hosted on GoDaddy. There is no server- ...

Material-ui table triggers onClick function multiple times instead of just once

One major issue that I am facing is that whenever I click on an object in the table, the onClick function is triggered for all objects instead of just the clicked one. My desired behavior is to display "Tutorial full info" only below the clicked object. Be ...

Steps to automatically populate the dropdown upon page load

Hello, I have a question regarding setting a value to a dropdown list in JavaScript. Currently, I am trying to execute this function during the onload event of the body tag. However, I am facing issues with setting the value. Below is the code: function s ...

What is the mechanism for invoking functions defined with the arrow syntax in Angular?

Referencing this code snippet from the tutorial at https://angular.io/tutorial/toh-pt4, specifically within the hero.component.ts file: getHeroes(): void { this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes); } After analyz ...

Guide to implementing external CSS in Material-UI for efficient styling without relying on Javascript

As I embarked on creating an application with the ReactJS framework and utilizing the Material-UI library, I noticed that all styles are currently being defined within Javascript. However, my preference is to style components using CSS. What steps can be ...

Displaying an Image Inside a Material-UI Data Grid Table

Hello there. I've been trying to incorporate an image into a material-ui data-grid table, but unfortunately, it's not working as expected. Can anyone point out what I might be missing in my code? I checked the documentation, but couldn't fin ...

Issue with converting string to Date object using Safari browser

I need to generate a JavaScript date object from a specific string format. String format: yyyy,mm,dd Here is my code snippet: var oDate = new Date('2013,10,07'); console.log(oDate); While Chrome, IE, and FF display the correct date, Safari s ...

Setting a fixed data value within a div for subsequent retrieval through a function

I found a helpful example that demonstrates how to convert numbers into words. You can check it out here. The function for converting numbers into words is implemented in the following HTML code: <input type="text" name="number" placeholder="Number OR ...

Eliminate jQuery's delayed blinking effect with the use of an event

Utilizing the mouseenter and mouseleave events, I have implemented a functionality to add a button (not actually a button) to an <li>. However, there seems to be a problem with my code. The button appears and disappears on mouseleave and mouseenter, ...

Error occurs in Query component when using a higher order component (HOC) due to element type

I've developed a custom higher-order component called withInfiniteScroll, designed to enable infinite scrolling functionality for a basic list of data. My aim is to integrate this HOC within Apollo's Query component, but I'm encountering an ...

I am encountering the ERR_STREAM_WRITE_AFTER_END error in my Node.js API. Does anyone know how to resolve this problem?

When I try to upload a file using the API from the UI, I encounter the following issue. I am interacting with a Node.js API from React.js and then making calls to a public API from the Node.js server. https://i.stack.imgur.com/2th8H.png Node version: 10. ...

Error: The variable $traceurRuntime has not been defined in the AngularJS application

Currently, I am utilizing [gulp-traceur][1] to convert es6 to js within my angularjs application (version 1.x). However, when attempting to compile a for loop, an error occurs: ReferenceError: $traceurRuntime is not defined It appears that I may need to ...

When attempting to call a bundle file using browserify from React, an unexpected character '�' Syntax error is thrown: react_app_testing/src/HashBundle.js: Unexpected character '�' (1:0

Hey there, I'm currently struggling with an unexpected unicode character issue. Let me provide some context: I've created a simple class called HashFunction.js that hashes a string: var crypto = require('crypto') module.exports=class H ...