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

Ways to conceal the contents of a page behind a transparent background div while scrolling

I created a Plunkr with the following markup: <body> <div class="container-fluid"> <div class="row"> <div class="col-sm-12"> <nav class="navbar navbar-fixed-top"> <div class="container-fluid"& ...

The URL is being modified, yet the page remains static in the React application

I've been working on setting up a router with react-router-dom, but I'm facing an issue where my URL gets updated without the page routing to the specified component. Here's a snippet from my App.js: import "./App.css"; import { Br ...

Unsure why my React component isn't triggering a re-render?

I encountered an issue when trying to update my component based on a state change. When I update the state outside of an HTTP call, the component updates correctly. However, when I try to do the same inside an HTTP get call, the state is updated but the ...

Exploring the usage of symbols within routes in the latest version of React Router

Transitioning from version 5 to version 6, it appears that regular expressions can no longer be used in the new version. Is there a simple solution for handling paths with dashes like this? The issue specifically lies with the dash character. <Route p ...

Guide to dynamically setting SCSS $variables in JavaScript after retrieving them from local storage in a React application

In my current situation, I am retrieving color combinations in hash values from the database through an API call and then saving them in localStorage for future use. However, I am facing a challenge when trying to access this data from localStorage and uti ...

Challenges with Hover Dropdowns in Bootstrap Navigation Menu

Check out this screenshot of a navbar PSD design I'm aiming for: To make my navbar dropdown show up upon hovering, I've implemented the following JavaScript: $('.navbar .dropdown').hover(function() { $(this).find('.dropdown-men ...

Modify CSS image according to the user interface language in asp.net

Is there a way to dynamically change the image based on different cultures in my ASP.NET webpage? I have successfully been able to switch strings using a resource file, but I am unsure how to handle images. Currently, I have an A tag with a specific clas ...

What steps do I need to take to extract the date and month from a single datepicker using the code below?

<div class="col-md-3 pull-left" style="padding:9px"> <input type="text" id="datepicker" class="form-control"> </div> The HTML and C ...

Should the element be scrolled beyond a fixed-positioned element

Is there a way to determine if an element is scrolled behind another element that is fixed at the top? I am looking to trigger some javascript when an element is positioned below a fixed element and every height or scrollTop thereafter. I am attempting t ...

The Google Visualization chart fails to display properly once CSS is applied

Struggling with a graph display issue here. It's quite perplexing as it works fine on older laptops and Safari, but not on Chrome or older versions of Firefox. Works like a charm on my old laptop and Safari, but fails on Chrome and Firefox (haven&apo ...

How can I ensure that Redux-saga waits for API calls to resolve instead of returning promises continuously? Is there a way to make "yield call" wait for API calls to complete?

Where I'm initiating the API request: function fetchCharacter(value){ return axios.get(`https://www.breakingbadapi.com/api/characters?name=${value}`) .then(res=>{ console.log(res.data) }) .cat ...

Tips on displaying tooltip specifically for displaying x values only in React charts

Currently, I have a line chart that displays only four values, yet my datasets contain more data points. The issue is that the dot on the line is shown for all datasets. Is there a way to show the circle pointer only for x values that are displayed? https ...

Issue with Material UI Menu not obtaining the accurate ID

My table requires an action menu button, but when it renders, it copies the last ID of the array instead. I'm struggling to identify the root cause of this issue despite trying multiple solutions that didn't address the problem. Below is the cod ...

The alignment of my divs is all out of whack -

Currently, I have styled my website to work perfectly in Firefox, but it's not appearing correctly in Chrome. You can see the layout at . My goal is to maintain the layout as seen in Firefox while also making sure it displays properly in Chrome and IE ...

Encountering an issue while setting up a Next.js project, I am struggling to find a solution despite trying various methods

I attempted to install Next.js, and even updated my npm version in order to create a new React project with the latest Next.js. However, I kept encountering the same error. Aborting installation. Unexpected error. Please report it as a bug: Error: spawn ...

Endless loop occurs with post and put requests while attempting to refresh authentication token

Every time the token expires in my application with NEXTjs and I attempt to make a post request, it gets stuck in a loop. The POST request returns 401, then the refresh-token returns 200 after attempting the post again, it returns 401, and the cycle repeat ...

Setting up Swiper in a ReactJS environment

I've been trying to incorporate Swiper for a slider in my React application, but it's not behaving as expected. Here's what I did: npm install Swiper Then I imported Swiper in the componentDidMount method of my component like this: import ...

What is causing Firefox to display an additional line in this section?

After much effort, I've been attempting to eliminate the extra spacing on this page in Firefox: Do you see the menu? If you compare it to Chrome, you'll notice that the menu is positioned too low beneath the background, giving the layout a broke ...

Assigning a new classification to the primary object in the evolving array of objects

I'm working with an element that loops through all the objects using v-for and has a CSS class named top-class{}... I need to dynamically add the top-class to the first object (object[0]) and update it based on changes, removing the old top-class in t ...

An issue arose when attempting to publish a project using react and Node.js on two different servers

I successfully created a React application and a Node API that are working together seamlessly. The React app was developed using vite.js and deployed on a hosting platform, while the node server is hosted on a VPS server. Here's a summary of the task ...