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

Identifying URL modifications in a UmiJS React web application: a step-by-step guide

In my application, I have a file called BasicLayout.jsx which passes props to the main components and renders child components within the layout. I am looking for an effective way to detect URL changes using the useLocation hook in the useEffect() of Bas ...

Is there a way to upload images or PDFs in a MERN project using the fetch API and save them in a specific folder within

I am encountering an issue while attempting to incorporate a new input field for adding files/images during user registration, with the intention of saving the image name in MongoDB and storing the image in a designated folder. Unfortunately, I am facing d ...

Unable to maintain checkbox state after page reload in React

I am currently working on creating a to-do list application using React and Material UI. Everything is functioning well except for the checkbox state. I am storing each to-do as an object in an array called todoList in local storage, like this: todoList i ...

Exploring various data promises in AngularUI router

I am attempting to utilize the $q service to resolve multiple promises using the $q.all() function with AngularUI router. However, I am encountering issues where it is failing or not functioning as expected. This snippet is from my configuration file that ...

having trouble transferring data from one angular component to another

I've been attempting to send data from one component to another using the service file method. I've created two components - a login component and a home component. The goal is to pass data from the login component to the home component. In the l ...

Is there a way to display a customized label in getOptionLabel method similar to renderOption in Material UI Autocomplete?

I have a requirement to display the total number of items in each option for the Autocomplete feature. While I am able to show this in expanded items, I am unable to display it when one is selected. Please refer to the image and code provided and suggest ...

Instructions for adjusting the size of my modal window when the keyboard appears?

While developing a next.js app, I encountered an issue with the chat modal. When the input field is in focus, I want to resize the modal height so that the keyboard popup does not hide the input field. I attempted to modify the DOM but could not get it to ...

What is the best way to manage the "open link in a new tab" action?

I am currently working on a project that involves displaying a series of resources on a web page. Each resource is stored as a record in a database with two fields: "url" and "visited." One issue I have encountered is that when a user clicks on a resource ...

Images are not appearing correctly on Chrome browsers when using Windows operating system

img tags seem to have unusual margins in Chrome, Edge, and Opera browsers, while Firefox displays them correctly. Queries What is causing these margins specifically in Chrome? The Devtool does not detect any margin properties. Is there a straightforward s ...

Examining the integration between React, Redux, and Redux-saga through comprehensive

I'm facing a challenge with structuring integration tests for my project setup, which looks like this: app/ global/ styles/ components/ scenes/ Home/ actions.js constants.js index.jsx reducer.js sagas.js ...

The function getElementbyId is not recognized

My JavaScript code is supposed to change the color of a button, but I'm running into an issue where it says that getting the button is not a function. Strangely enough, the same function (with the same capitalization and case) works perfectly just a f ...

Exploring the width of Bootstrap 5 Tab Pane content

My issue lies with the content width of my tab panels - specifically, it doesn't work well with columns. I am unable to divide a tab-pane as col-md-7 and col-md-5 (refer to the screenshot below). I am unsure of how to resolve this issue. <div clas ...

Every time I try to read a file using JavaScript, I keep running into the error: "Uncaught TypeError: fs.readFile is not a function." It's really frustrating

const fileSystem = require('fs'); fileSystem.readFile('analogData.txt', 'utf8', (error, content) => { if (error){ console.log(error); } else console.log(content); }); I am attempting to retrieve data f ...

I am facing errors while running npm run build in my Vue CLI project, however, npm run dev is running smoothly without

I am encountering an issue when running npm run build as it generates a series of errors, whereas npm run dev runs smoothly without any errors. I have attempted to resolve this by modifying the public path in webpack.config.js to ./dist, but unfortunately ...

Utilize PHP, JSON, and JavaScript to dynamically insert personalized information into HTML

Struggling, I turn to this site for help despite the dislike for "spot my mistake" code. My website urgently needs access to user-specific data from a PHP database, then convert that data into a JSON file and display it in an HTML header. The database cont ...

Utilizing Bootstrap for Efficient Image Alignment

I'm encountering an issue with my code and I am unsure of how to fix it. The current state of my code is different from the desired outcome https://i.sstatic.net/Ti1kK.jpg As you can see, the image above does not match the appearance of the image I ...

What is the best way to generate a complete PDF of a webpage using pdfmake?

I'm currently developing a web application and facing the task of converting an HTML page, which contains multiple tables and datatables, to a PDF format. To achieve this, I've chosen to utilize the library pdfmake. Below is the script that I ha ...

The conventional method for including React import statements

I'm curious if there is a standard convention for writing import statements in React. For instance, I currently have the following: import React, { useState, FormEvent } from 'react'; import Avatar from '@material-ui/core/Avatar'; ...

Encountering Challenges When Trying to Upload File onto Azure Blob Storage

My current project involves integrating file uploads to Azure Blob Storage. The backend setup using Node.js with Express and @azure/storage-blob is already done, but I'm facing challenges with the frontend implementation. I need guidance to ensure pro ...

What is the best way to create a @mixin incorporating variables to easily reference breakpoints using custom aliases?

Currently in the process of constructing a website using SASS coding, I have created several @mixins for Media Queries that will be utilized later with the @include directive. The structure of these mixins is as follows: _standards.sass // Media queries @ ...