Is it possible to modify the CSS styling in React using the following demonstration?

I am attempting to create an interactive feature where a ball moves to the location where the mouse is clicked. Although the X and Y coordinates are being logged successfully, the ball itself is not moving. Can anyone help me identify what I might be overlooking?

This code snippet pertains to a Typescript React component.

  const PlayArea = () => {
  let top = 'inherit';
  let left = 'inherit';
  
  document.addEventListener("click", function(e){
    console.log((e.clientX + 25) + 'px')
    top = (e.clientY - 25) + "px";
    console.log(top)
    left = e.clientX - 25 + "px";
  });
  return (
    <>
      <div className="ball" style={{ transform: `top ${top}, left ${left}` }}></div>
    </>
  );
};

export default PlayArea;

The following CSS rules apply:

.ball {
  height: 100px;
  width: 100px;
  border-radius: 50%;
  background-color: #0b8027; 
  position:absolute;

}

Answer №1

Declare your top and left variables as state objects and update them within the click event callback.

const [mouse, setMouse] = useState({})

useEffect(() => {
  const event = (e) => {
    setMouse({ top: `${e.clientY - 25}px`, left: `${e.clientX - 25}px` 
  }
  document.addEventListener("click", event);
  });
  return () => document.removeEventListener("click", event)
}, [])

return (
    <>
      <div className="ball" style={{ top: mouse?.top, left: mouse?.left }}></div>
    </>
);

Avoid using transform for the top and left styles. Instead, directly set them and let the element's position property handle its placement based on the values you provide.

Additionally, it's recommended to initialize your event listener on component mount and remove it when the component unmounts using the useEffect hook and cleanup function.

Answer №2

To trigger a re-render of the component, you must utilize the state feature. Define your top and left variables within the state as shown below and attach the event listener after your component has been mounted.

import { useEffect, useState } from 'react';

const PlayArea = () => {
    const [state, setState] = useState({
        left: 'inherit',
        top: 'inherit',
    });

    useEffect(() => {
        document.addEventListener('click', (e) => {
            setState({ left: `${e.clientX - 25}px`, top: `${e.clientY - 25}px` });
        });
    }, []);

    return (
        <>
            <div className="ball" style={{ transform: `top ${state.top}, left ${state.left}` }} />
        </>
    );
};

export default PlayArea;

Since you are attaching the event listener to the document object, ensure that you have the position: fixed property unless you have a relative class for the div element you created.

.ball {
  height: 100px;
  width: 100px;
  border-radius: 50%;
  background-color: #0b8027; 
  position:fixed;

}

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

Tips for creating an infinite repeating loop in jQuery

I'm attempting to create a jQuery infinite loop featuring images within a div. I've experimented with using the setInterval function, but encountered an issue where the animation starts after a 3-second delay and does not seamlessly repeat itself ...

Updating the appearance of tabs in React Native Navigation dynamically during runtime

I am currently working with the startTabBasedApp API, which includes three tabs in my app. I have a requirement to change the background color of the tabBar for specific screens dynamically. Is it possible to achieve this at runtime? For instance: Scree ...

Updating information within AngularJS select boxes

On my page, I have 3 select boxes. When a user selects an option in the first select box, I want the options in the second select box to update based on the value selected in the first one. Similarly, I want the options in the third select box to change w ...

Input for uncomplicated changing identifier

I am looking to create types for dynamic keys that will be of type number. I have two similar types defined as follows: type UseCalculatePayments = () => { totalPayments: number; aggregate: number; condition: boolean; }; type UseCalculateCommissio ...

Saving table sorting in Redux with Ant Design Table

I am currently working with Antd Version 4.2.2 in my ReactJS project. Specifically, I am utilizing the Ant Design < Table /> component. My goal is to save the sorting order that is applied to the columns into Redux state. Here is my current approa ...

Looking for a way to prevent a div element from scrolling in JQuery Mobile?

Here is my implementation: http://jsfiddle.net/coderslay/Lhb5Y/ I have content structured like this: <div data-role="content"> <div><!--Contains a button --></div> <div><ul>..<!--Contains a list -->...</ ...

Unexpected Token < in Jest/Enzyme testing for SVG Sprites

I'm encountering an issue while attempting to create a snapshot test using Jest and Enzyme on a component that utilizes SVG sprites. The package I am using is svg-sprite-loader, which can be found at: https://github.com/kisenka/svg-sprite-loader Bel ...

What is the best way to automatically resize a React Material Slider component?

Is there a way to set the slider to automatically adjust its width? Currently, I can only specify a fixed width in the css or leave it blank, resulting in a zero-width slider. What I need is to have the label on the left (with variable size) and then the ...

Unexpected Behavior: using setTimeout in a ReactJS class component leads to incorrect value retrieval

App Component: class App extends React.Component { constructor() { super(); this.state = { user: 'Dan', }; } render() { return ( <React.Fragment> ...

Issue with populating virtual IDs in NestJS mongoose schema containing an array of schemas

In the schema provided below, I have defined the structure for Map, Marker, and Desk: export type MapDocument = Map & Document @Schema({ timestamps: true, versionKey: false, id: true }) export class Map { constructor(partial?: Partial< ...

Transferring files with Node.js via UDP connections

I'm currently working on setting up a basic Node.js server that is designed to receive files from clients through UDP. The challenge I'm facing is that whenever I attempt to send a large file (anything over 100kb), the server appears unresponsive ...

"Transforming icons into text within the material-ui-table component: A step-by-step guide

If I want to replace the + icon in a material-table row with text like "ADD ROW," is there any way to do it? The material-table only accepts the icon object, and there doesn't seem to be another prop that allows for text replacement. I am utilizing th ...

Learn the steps to export a constant value in Next.js using React!

I need to export the constant value views from BlogPost.js to blog.js. This is the content of BlogPost.js: import React from 'react'; import useSWR from 'swr'; import format from 'comma-number'; import { useColorMode, He ...

Obtain the URL of the parent window from a modal dialog using JavaScript

What is the proper syntax for obtaining the URL (specifically, the PATH) of the parent window from a modal dialog box in Internet Explorer. I have attempted several variations such as: window.opener.document.location window.opener.location this.opener.do ...

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 ...

Establish a connection between a React variable and state management

In my codebase, I have an external module file named Task.ts. It contains the following: const taskList: Task[] = []; Class Task { ... } export { Task, taskList } The taskList is a list of Task objects that can be modified by the Task class. Now, i ...

How can I properly integrate multer with Node and Express in this situation?

I've been working on setting up a route for uploading photos, but after making some changes, it has stopped functioning and I'm not sure how to fix it. const multer = require('multer'); // MULTER STORAGE const multerStorage = multer.di ...

I'm looking for guidance on how to properly implement onChange in this particular script. Any help with the correct syntax

Can someone help me with the correct syntax for writing onChange in this script? I want to integrate these phpcode into my script. Here is the Javascript code: ih+='<div class="form-group drop_bottom" id="select_one_'+extra_num+'">< ...

Using React for passing data

In the snippet found in "CameraPage.tsx", there is a logical function that is responsible for fetching camera images. This function simply makes a GET request to search for images stored in the backend, which will later be displayed on the FrontEnd. The op ...

Exploring the Differences Between JQuery Ajax Page Fragment Retrieval with Find and Filter

I am currently testing out the following Ajax code for a form. $('body').on('submit','#sign-in', function(e) { e.preventDefault(); var data = $(this).serialize(); var url = $(this).attr('action'); ...