Animating elements using CSS dynamically

Currently, I am developing a unique roulette feature that spins horizontally (from right to left). I'm exploring ways to dynamically utilize @keyframes to apply translateX() with values based on the outcome of each spin. For example, if the result of a round is 5, the roulette will move a certain number of pixels to land on the corresponding number specified by the server.

Below is the code snippet for the roulette functionality:

import React, { useState, useEffect } from "react";
import { socket } from "../../App.js";

import "./roulette.css";

export default class Roulette extends React.Component {
  constructor(props) {
    super(props);
    this.socket = socket;
    this.roulette = React.createRef();
    this.state = {
      result: null,
    };
  }

  componentDidMount() {
    this.setState({
      backgroundPositionX: (this.roulette.current.offsetWidth - 78) / 2
    });
    this.socket.on("roulette.roll", position => {
      //TODO: Determine the amount of translation needed from the server  
});
  }

  render() {
    return (
      <div className="main-r flex items-center justify-center">
        <div ref={this.roulette} className="roulette relative">
          <div
            style={{backgroundPosition: this.state.backgroundPositionX + "px" + "0"}}
            className="roulette-bg h-full w-full" 
          ></div>
          <div className="roulette-marker absolute"></div>
        </div>
      </div>
    );
  }
}

Answer №1

To implement this functionality, you can initialize it within the componentDidMount() method as shown below:

export default class Roulette extends React.Component {
  constructor(props) {
    super(props);
    this.socket = socket;
    this.roulette = React.createRef();
    this.state = {
      result: null,
      backgroundPositionX: null
    };
  }

  componentDidMount() {
    this.setState({
      backgroundPositionX: (this.roulette.current.offsetWidth - 78) / 2
    });
    this.socket.on("roulette.roll", position => {
        this.setState({
            backgroundPositionX: position
        });
      //TODO: Retrieve from the server how much pixels should be translated  
});
  }

  render() {
    return (
      <div className="main-r flex items-center justify-center">
        <div ref={this.roulette} className="roulette relative">
          <div
            style={{backgroundPosition: this.state.backgroundPositionX + "px"}
            className="roulette-bg h-full w-full" //The roulette background image, that is suposed to translate when the result is give is in this div
          ></div>
          <div className="roulette-marker absolute"></div>
        </div>
      </div>
    );
  }
}

Alternatively, you have the option of using JavaScript to manipulate the styles of elements on the page through the ElementCSSInlineStyle feature. You can find more information about this here.

Incorporating the translation suggested by @yuri-gor would involve something like this within your componentDidMount():

const bgElement = window.document.querySelector('.roulette-bg');
bgElement.style.transform = 'translateX(42px)';

Answer №2

If I understand your needs correctly - you are looking for CSS transitions rather than keyframes.

transition: transform 5s;
element.style.transform = 'translateX(42px)';

It's important to note that animating through changing the transform property results in a smoother rendering.

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

Horizontal rule located within a table but spanning the entire width

I wrote the following code: <table> {item.awards.map((obj,i) => <tbody> <tr> <td>Name</td> <td>:</td> <td>{obj.title}</td> </tr> ...

Guide to mapping objects in React

I am currently working on mapping a JSON object. The structure of the JSON is as follows: { "Status": true, "discounts": { "broker": { "discount": "1" }, "dealer": { ...

Navigate to a New Page post Dropdown Selection

Currently working on developing a website using Github Pages where I need users to be directed to a specific page after choosing the final option. I am extracting data from a JSON file. I attempted to include an anchor tag in the JSON but it does not red ...

Deactivated Ajax pagination when clicking on a disabled list item

Is there a way to disable the click functionality for the First Page and Previous button when they are disabled? Similarly, can we prevent clicking on the Next and Last buttons when you are on the last page? I have tried using off() and unbind() methods wh ...

To make the label font size larger when it appears on hover in chart.js

I have been attempting to increase the font size of labels that appear on hover in chart.js. I am also trying to customize the text of the label, but so far, I have not been successful in increasing its font size. var myPieChart = new Chart(ctxP, { ...

Achieve proper alignment between a label and textbox using CSS styling

While the title may lead you to believe this is just another CSS issue, it's actually a bit different. I have a textbox with a placeholder property and a applied CSS class. Now, I need to add a label to signify it as a mandatory field. The problem ari ...

Is it possible to submit a form without redirection or iframes? (Seems to be ineffective on mobile devices)

I have successfully implemented a submit function on my desktop using an iframe, which works without any redirects. However, when I visit my site on a mobile device (using Chrome or Safari), the page automatically redirects to the endpoint and stops load ...

Strip the date after converting from milliseconds to a date

When my server back end sends the time value as milliseconds (1479515722195), I use a library function to convert it to a date format like Sat Nov 19 2016 11:35:22. Now, I need to figure out how to separate the date and time components. I only require th ...

The scrolling behavior of Chrome tabs or bookmarks can impact the functionality of an Angular

I recently came across a strange problem with my angularjs page that includes a slick carrousel. In the controller, I have code that listens for the $destroy event to remove certain injected elements by slick. However, I noticed that whenever I scroll ov ...

Error in React Native: The function this.setState is not defined. (The function "this.setState" is not a valid function)

I am working on integrating JSON data from an open source API and storing it as a state. However, I am facing challenges in saving the JSON data into the state which I want to use for city matching. It would be really helpful if someone could provide assis ...

Issue with jQuery functionality when page is loaded through AJAX request

My index page currently has jQuery and a js file for a slider plugin loaded. I am using an on click event to load an external page using .load. Here is the code snippet: //jQuery loaded from Google CDN here (in head) jQuery( document ).ready(function() { ...

Tips for centering text and icon on a Bootstrap navigation bar

I am currently developing an Angular 4 application that includes a navigation bar with text and font awesome icons. While the UI looks good in web view, I'm facing alignment issues when it comes to mobile view (minimized screen). Despite my efforts, ...

Having trouble with altering the placeholder text of the submit button?

.RegisterForm { height: 35em; width: 25em; } .LoginForm { height: 20em; width: 25em; } .RegisterForm, .LoginForm { position: absolute; ...

Issue with Bootstrap 5 Dropdown not toggling back

<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Creative Admin Panel</title> <link rel="stylesheet" href=&q ...

An unconventional way to display an image using the :before pseudo-element and a data attribute in CSS

My goal is to use the :before pseudo-element to set an image background, as I plan to overlay content on top of it. In the past, I have dynamically set a data attribute with :before for other purposes. Question: Is there a way to change the number using ...

I'm still searching for a proper solution on how to access JavaScript/jQuery functions within Colorbox

For my website, I am utilizing PHP, jQuery/JavaScript, Colorbox (a jQuery lightbox plugin), Smarty, and other tools. Currently, I am working on displaying data in a popup using the Colorbox plugin. However, I am facing an issue with calling a JavaScript fu ...

AngularJS - Textarea not resetting content on ng-click event

Having an issue with my textarea. When attempting to clear it using ng-click, nothing happens... Can anyone provide assistance? Here is my code for testing: My app If you prefer to view it here: HTML : <div ng-controller="Ctrl1"> <d ...

Setting up your React Environment: A Step-by-Step Guide

I'm currently experiencing difficulties setting up my react environment. After executing the command npm create-react-app my-app, I encountered errors. The error messages are as follows: npm WARN npm npm does not support Node.js v20.12.2 npm WARN npm ...

Do not include .js files in React.js build process

Is there a way to prevent a specific .js file from being included in the npm run build I attempted to exclude it by adding: "build": "react-scripts build && rm -rf build/config-local.js", to package.json, but I received the following error: ...

The ng-repeat directive fails to acknowledge changes in the model

I'm having trouble iterating over the properties of a model that I am updating. Below is the code snippet from my controller: app.controller('VariantsController', ['$http', function($http){ var ctrl = this; this.cars = []; ...