What is the best way to manage classNames dynamically in React with Material-UI?

I am wondering how to dynamically add and remove classes from an img tag. My goal is to change the image automatically every 2 seconds, similar to Instagram's signup page. I am struggling to achieve this using the material-ui approach. Below is a snippet of my code where I want to periodically add and remove certain classes.

<div className={classes.phoneImageWrapper}>
  <img src={Phone1} alt="instagram" className={classes.phoneImage} />
  <img src={Phone2} alt="instagram" className={classes.phoneImage} />
  <img src={Phone3} alt="instagram" className={classes.phoneImage} />
  <img src={Phone4} alt="instagram" className={classes.phoneImage} />
  <img src={Phone5} alt="instagram" className={classes.phoneImage} />
</div>

Additionally, here are the styles I intend to toggle between adding and removing phoneImageAnimation and phoneImageVisible classes to the img tag every 2 seconds:

phoneImageWrapper: {
  margin: "10px 0 0 151px",
  position: "relative",
},
phoneImage: {
  top: 100,
  left: 0,
  position: "absolute",
  width: 240,
  height: 427,
  opacity: 0,
  visibility: "hidden",
},
phoneImageAnimation: {
  transition: "opacity 1.5s ease-in",
  zIndex: 2,
},
phoneImageVisible: {
  opacity: 1,
  visibility: "visible",
}

https://i.stack.imgur.com/JqBdj.png

Answer №1

If you want to incorporate a timing function in your React component, you can utilize the setInterval method within the useEffect hook as shown below.

 const [activeIndex, setActiveIndex] = useState(0);

 const images = [
   <img src="/1.webp" alt="1" />,
   <img src="/2.png" alt="2" />,
   <img src="/3.webp" alt="3" />
 ];

  useEffect(() => {
    let timer = setInterval(() => {
      setActiveIndex((prevIndex) => {
        return (prevIndex + 1) % images.length;
      });
    }, 2000);

    return () => {
      clearInterval(timer);
    };
  }, []);

To add animation effects, you can make use of the react-transition-group library.

I have prepared a demonstration for you. Check it out on this CodePen link.

Answer №2

Utilize the clsx library, a convenient tool designed for this specific purpose.

Set up a variable called image to cycle through each image (based on index or name) every 2 seconds.

<div className={styles.imageContainer}>
  <img src={Image1} alt="example" 
       className={clsx(styles.image, image===0 && styles.visible )} />
  <img src={Image2} alt="example" 
       className={clsx(styles.image, image===1 && styles.visible )} />
  <img src={Image3} alt="example" 
       className={clsx(styles.image, image===2 && styles.visible )} />
  <img src={Image4} alt="example" 
       className={clsx(styles.image, image===3 && styles.visible )} />
  <img src={Image5} alt="example" 
       className={clsx(styles.image, image===4 && styles.visible )} />
</div>

Answer №3

To dynamically change the state of a class, you can utilize the combination of setInterval and useState.

For example, if you have an array of different classes that you wish to rotate through every 2 seconds:

const classes = ['class1', 'class2', 'class3'];

You would also need a state variable to keep track of the current class index:

const [currentIndex, setCurrentIndex] = useState(0);

In a useEffect hook, you can set up an interval to update the index state:

useEffect(() => {
    setInterval(() => setCurrentIndex((currentIndex + 1) % classes.length), 2000);
});

Finally, apply the current class from the array using the className attribute:

<div className={classes[currentIndex]}></div>

And there you have it - a simple way to cycle through different classes dynamically!

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

Is it possible to merge JavaScript files exclusively using encore?

I am working on a Symfony project with a Twitter Bootstrap template where the assets are hardcoded in Twig. I would like to use Encore to manage assets, but I want it to only combine JavaScript files without compiling them further. Is there a way to confi ...

What is the best approach to synchronize checkboxes with boolean values in my data model?

I've spent hours searching through similar questions, but haven't found a solution that perfectly matches my issue. What I need is to have a checkbox automatically checked based on a true/false value in my data using data binding. While I can suc ...

Updating a document using the nano module in CouchDB is not supported

I am currently utilizing the Node.js module known as nano Why is it that I am unable to update my document? I need to set crazy: true and then change it back to false. This is the code I have: var nano = require('nano')('http://localhost ...

Reacting to multiple checkboxes in a check handling system

In my latest project, I have designed a component that utilizes multiple checkboxes generated within a .map function. While testing the functionality, it came to my attention that users could select more than one checkbox at a time. This is not ideal as th ...

The reason behind the creation of .pnp.loader.mjs and .pnp.cjs files by yarn

While working on my React project with Vite, I noticed that when using yarn to start the "live server," two new files are created: .pnp.loader.mjs and .pnp.cjs. Can anyone explain what these files are for? I've never come across them before as I usual ...

How to insert a new document into a MongoDB collection with Mongoose

Consider a scenario where my existing collection called fruits is structured as follows: {"_id" : ObjectId("xyz...."), "name" : "Apple", "rating" : 7} {"_id" : ObjectId("abc...."), " ...

When attempting to append a script element and the operation fails due to lack of authorization, which error is typically thrown

I am trying to handle a particular failure in this JavaScript code: var script = $wnd.document.createElement('script'); script.setAttribute('src', url); script.setAttribute('type', 'text/javascript'); When the URL ...

Issue with rendering React Toastify

I'm running into an issue while trying to integrate react toastify into my react vite application. Specifically, I keep getting an error related to useSyncExternalStore even after attempting to switch to version 9 of react toastify. My React version i ...

Encountering error TS2307: Module 'redux' not found when trying to implement redux in Angular 7

Currently, I am diving into the world of Redux and attempting to integrate it into my Angular 7 project using ng2-redux. However, upon visiting the npm page, I discovered that the recommended approach was to install it with npm install @angular-redux/store ...

What is the process for adding color to the rows of a table?

Hello, I have a table with various fields that include: I am looking to assign colors to entire rows in the table based on certain criteria. For example, if the ASR value falls between 75 and 100, it should be assigned one color; for values between 50 and ...

Global variables become undefined after utilizing jQuery's getScript() method for assignment

I have a few global variables named var1, var2, and so on... Instead of immediately initializing these variables, I wait until later to instantiate them using jQuery from a constructor located in a separate javascript file. However, after this instantiat ...

How can I retrieve x-data from an external file using Alpine.js?

I recently started exploring Alpine.js and grasped the fundamentals, but I'm facing challenges when trying to move functions outside of inline script tags. Consider this snippet from index.html: <div x-data="{ loading: false }"/> &l ...

Transitioning jQuery .load and the usage of sorttable.js for sorting data

My jQuery code snippet is as follows: $("#loadBtn").click(function(){ $('#div1').delay(200).slideUp('slow') .load ('page2.php #div2').hide().delay(300).slideDown('slow'); return false; ...

Vue Router does not enforce redirects

I am currently facing an issue where the requireAuth() function is being called repeatedly, causing a loop. I only want to display pages when the user is logged in. This is the code snippet I am using: // Routes const routes = [ { path: &apos ...

What is preventing me from using JavaScript to remove this class?

Struggling to implement a skeleton loading screen with CSS classes and JavaScript. The idea is to apply the 'skeleton' class to elements, style them accordingly, then remove the class using a timeout set in JavaScript. However, I'm encounter ...

Re-rendering a Highcharts chart for optimal display

I have implemented Highcharts to showcase a set of data through different types of charts - Area chart, Line chart, and Bar chart. By default, the page loads with the Area chart displayed. Upon clicking a button, I switch to displaying the Line chart and t ...

Transmitting form data inputted by the user to a modal that resides in the same component, all without the need for child or parent components or

In need of a solution where users can input answers to questions and have all the entered data displayed in a popup alongside the respective question. If a user chooses not to answer a question, I do not want that question or any related information to be ...

What is the best way to navigate my Page while my Dialog Component is displayed?

Is there a way to enable scrolling on the background when a dialog component opens up? By default, scrolling is disabled when the dialog appears. How can we allow scrolling in the background? Here is the code snippet: import React, { useState } from &apos ...

Do you need to redeclare the type when using an interface with useState in React?

Take a look at this snippet: IAppStateProps.ts: import {INoteProps} from "./INoteProps"; export interface IAppStateProps { notesData: INoteProps[]; } and then implement it here: useAppState.ts: import {INoteProps} from "./interfaces/INo ...

Updating a property of a JavaScript class using a callback function inside the class method after an AJAX request

Here is the code snippet from my JavaScript file: var myApp = myApp || {}; myApp.TestClass = function () { this.testProperty = null; } myApp.TestClass.prototype = { constructor: this, testMethod: function () { var testClass = this; ...