Tips for sending a value or props to a CSS file

Is there a way to dynamically update the x and y position based on user clicks, and then apply these changes to the top and left properties of a div?

.dataCardAbsolute {
  position: absolute;
  top: 100px;
  left: 300px;
  overflow: auto;
}

React.useEffect(() => {
    document.body.addEventListener('click', (event) => { setPosition([event.pageX, event.pageY]) })
}, []);

<div
  className={{styles.`dataCardAbsolute-${}`}} //trying to figure it out...
  className={styles.dataCardAbsolute}         
>

Can anyone suggest a method for sending the updated position values to the CSS file?

Answer №1

If you're looking to enhance your CSS skills, one cool technique you can experiment with is utilizing CSS variables within your stylesheets.

CSS variables offer the flexibility to define default values directly in the "style" attribute of a div element.

Here's a neat example to illustrate this concept:

document.addEventListener("DOMContentLoaded", () => {
  let button = document.getElementById("buttonID");
  let item = document.getElementById("itemID");
   
   let toggle = false;

  button.addEventListener("click", () => {
    item.style = toggle ? "--radius: 50%;" : "--radius: 20%;";
    toggle = !toggle;
  });
});
html, body {
  width: 100%;
  height: 100%;
}

.button {
  background-color: aliceblue;
  width: 20%;
  height: 20%;
}

.item {
  border-radius: var(--radius);
  
  background-color: green;
  width: 30%;
  height: 40%;
}
<button class="button" id="buttonID">Resize the item</button>
<div class="item" id="itemID" style="--radius: 50%;"></div>

Answer №2

It appears that the setter function's state is related to position, which means updating it would require inline style adjustments. The most straightforward approach would be to update it using inline styles.

 <div
      className={styles.dataCardAbsolute}
      style={{ top: `${position.top}px`, left: `${position.left}px` }}
    >

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

Activate CSS transition only when not in active state

I have a situation where I want to change the background color immediately upon hovering over an element, and then revert back to the original color when no longer hovering. The CSS for this is straightforward: #el { background-color: black; } #el:hov ...

The useCallback hook provides access to the previous state value

One challenge I'm facing involves the useCallback hook, which is responsible for updating a state based on certain filtering criteria. const onAcccountChange = useCallback( (e: React.ChangeEvent < HTMLInputElement > ) => { if (dat ...

Is it possible for Angular's `HttpClient` to use complex property types in the `.get()` generics aside from just `string` or `number`?

After spending an entire day researching the topic, I've hit a dead end. All my efforts have only led me to discover one thing—omission. None of the information I've come across mentions whether you can utilize non-simple types (such as string ...

Bringing elements into perfect harmony in Angular

Seeking guidance on HTML alignment using bootstrap for prebuilt components like buttons. Struggling with aligning divs and looking to learn more about grouping them together for proper alignment. Goal is to center elements on screen one above the other. ...

Tips for implementing a single function across multiple HTML classes using JavaScript

For the past few days, I've been struggling with a JavaScript issue as a newcomer to the language. $(document).on('click', '.content-click', function(){ $(".content-click span").toggleClass("clicked"), $(".content-view") ...

react-chart2: The 'map' property is not defined and cannot be read

I am currently working on creating a bar chart using react-chartjs-2, but I keep encountering an error that says: Cannot read properties of undefined (reading 'map'). This is my first attempt at creating a Chart and I'm trying to figure out ...

How can you show a green check mark next to an input field in AngularJS after inputting valid data?

I am diving into the world of AngularJS and Angular Material with my web application. As a beginner in AngularJS and Angular Material, I need some help. My current task is to display a green checkmark next to an input field only when valid data is entere ...

"Adaptive Material UI design that adjusts according to the size of the

In my current project, I am working with React and MaterialUI to develop a system that will showcase widgets within another web site that is not based on React. One of my main goals is to ensure that these widgets are responsive, adapting to their containe ...

Determine the starting position of a div's CSS bottom using jQuery before the hover animation begins

Currently, I am in search of the CSS value 'bottom' for each div that belongs to the 'shelf-info-text' class. These particular divs can be found inside a parent div called 'shelf-item'. The bottom value is determined automati ...

retrieve data from a form using reference values

Trying to send data using the following form: import React, { Component } from 'react'; class ToDoForm extends Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } handl ...

Repositioning with Flexbox: shifting the middle element to a new line

I have a flex item that contains three divs. ┌────────────────────────────────────────┐ | WRAPPER | | ┌─────────┬─ ...

Tips to prevent the return of undefined when a condition is not satisfied

I'm currently working on a react app and I have an array of objects (items) that I want to iterate over in order to display each object based on its index. I am using useState to set the index, which is updated when the user clicks a button. const ...

You need a function property for the child component to be updated

I recently encountered an unusual issue with my React components that has left me puzzled. Here is a condensed version of the app: class Child extends React.Component { componentDidUpdate(prev) { if (!prev.isActive && this.props.isActive) ...

The process of compiling with react-scripts suddenly crashes, leaving behind no error message except for a vague reference to running out of memory. On

I'm currently facing an issue while building my app using create-react-app. Previously, there were no problems with the build process, and I have not updated npm or node versions since the last successful build. When I run the build command, this is ...

When the React Redux store is updated, the component does not automatically re-render

I'm a beginner in Redux and facing an issue with re-rendering after the store is updated. Despite going through similar problems on SO, I still can't resolve my specific problem. My application consists of a monthly task calendar with multiple t ...

Issue with Tailwind CSS shadow and transition failing to work after activating JIT mode

After enabling tailwind JIT mode in my project, I encountered an issue where the transition stopped working and the shadow disappeared. Despite closely following instructions from a Youtube tutorial, I have yet to find a solution. Any suggestions would be ...

Is there a similar alternative to {useLocation} provided by 'react-router-dom' that can be used in Next.js?

import { useLocation } from 'react-router-dom'; Currently utilizing Nextjs, I'm seeking assistance in finding an alternative for useLocation ` import Link from 'next/link'; import { FC } from 'react'; import {useRout ...

Expand the display on mobile devices

What is the solution for adjusting a table on mobile view? I am aiming to achieve: https://i.sstatic.net/YkKAW.png However, it currently looks like this: https://i.sstatic.net/GW5mX.png Here are my code snippets: <script src="https://cdnjs. ...

How can I insert a item into an Array using JavaScript code?

My instructor set up an array in my JavaScript file that is off limits for me to modify. My task is to add new objects to it through code without directly manipulating the existing array. Here's a snapshot of what my array contains: const words = [{ ...

Difficulty with spacing in HTML/CSS styling

Here is what I'm currently working on: link to jsfiddle code * { margin: 0; padding: 0; } html { height: 100%; } header, nav, section, article, aside, footer { display: block; } body { font: 12px/18px Arial, Tahoma, Verdana, sans- ...