Fade-in a new, revised text after fading-out the original text in ReactJS

I have a bunch of p elements that I'd like to cycle through, fading in one at a time and then replacing it with the next. Here is the jQuery example on CodePen: https://codepen.io/motion333/pen/EBBGVM

Now, I'm attempting to achieve the same effect using React with the following code:

useEffect(() => {
        (function() {

            var quotes = document.getElementsByClassName('tagline-text');
            var quoteIndex = -1;

            function showNextQuote() {
              ++quoteIndex;
              document.querySelectorAll(".tagline-text")[quoteIndex % quotes.length].fadeIn(1000).delay(1000).fadeOut(1000, showNextQuote);
            }

            showNextQuote();

          })();
}, []);

Here's the container element:

<div className="tagline h-100 d-flex flex-column align-items-center justify-content-center">
    <p className="tagline-text">Your Business</p>
    <p className="tagline-text">Your Brand</p>
    <p className="tagline-text">Your Content</p>
    <p className="tagline-text">Your Portfolio</p>
    <p className="tagline-text">You.</p>
</div>

However, when I run the code, I encounter this error message:

Uncaught TypeError: document.querySelectorAll(...)[(quoteIndex % quotes.length)].fadeIn is not a function

Answer №1

that should work.

const { useState, useEffect } = React;

const items = ["Your Business", "Your Brand", "Your Content", "Your Portfolio", "You."];
const time_between_content = 2; // show content for 2s before fading out.
const transition_duration = 0.5;

const App = () => {
  const [displayContent, setDisplayContent] = useState(0);
  
  useEffect(() => {
    const timerId = setInterval(() => {
      setDisplayContent(p => {
        if(p === items.length - 1) p = -transition_duration;
        else p = p + transition_duration;
        return p;
      });
    }, time_between_content * 1000)
    
    return () => clearInterval(timerId);
  }, [])

  return <div className="pContainer">
    {items.map((item, index) => <p key={index} style={{ opacity: `${displayContent === index ? 1 : 0}`, transitionDuration: `${time_between_content + transition_duration}s` }}>{item}</p>)}
</div>
}

ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <App />
);
.pContainer {
  position: relative;
}

.pContainer p {
  font-size: 36px;
  font-weight: bold;
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  transition-property: opacity;
  transition-timing-function: ease-in-out;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

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 there a way to horizontally center a content container in Flutter similar to a "max-width" container in CSS?

How can I create a centered content box like this in Flutter?: .content-box { margin-left: auto; margin-right: auto; width: 100%; max-width: 600px; background-color: blue; height: 100vh; } <div class="content-box"> Cont ...

Dealing with a routing issue in node.js/express involving JavaScript and CSS

I'm facing an issue. I need to set up a route from localhost.../cars to localhost../bmw/x1 On the localhost../cars page, there's a button that, when clicked, should load localhost../bmw/x1 This is the JavaScript code I have: const express = req ...

Implementing the Upload Feature using AngularJS

Currently, I'm facing a challenge in implementing an upload button on my webpage using AngularJS and Bootstrap. Specifically, I am having trouble assigning the (upload) function to that button in AngularJS. The goal is for the button to enable users t ...

Using jQuery to fetch and display content only when the user hovers over

Looking to optimize page loading speed by minimizing the loading time of social icons such as Facebook Like and Twitter follow buttons. Considering displaying a static image of the like buttons initially, with the actual buttons appearing on mouse hover. ...

Sharing state between components in NextJS involves using techniques like Context API, passing

I am trying to pass state between pages in Next.js. In my App.js, I have wrapped it in a context provider like this: import { useRouter } from 'next/router' import { ClickProvider } from '../context/clickContext' function MyApp({ Compo ...

Changing the name of a file using NPM

Is there a way to change the name of a specific file in npm scripts? I need to modify files for distribution, but they must have different names than the original... I attempted using orn, however it only works on the command line and not as an npm script ...

Splitting Angular modules into separate projects with identical configurations

My Angular project currently consists of approximately 20 different modules. Whenever there is a code change in one module, the entire project needs to be deployed. I am considering breaking down my modules into separate projects for individual deployment. ...

Employing setTimeout within a repetitive sequence

function displayColors() { $.each(colors, function(index) { setTimeout(function(){ revealColor(colors[index]); }, 1000); }); } I'm attempting to create a loop where the revealColor function is executed every second until all colors ...

What causes my input field to lose focus in React.js after typing just one character?

My react.js component is experiencing an issue where the input field loses focus whenever a character is typed. To continue typing or editing, I have to click on the input field again. What could be causing this problem? Below is the code snippet in quest ...

Saving Files in Your React Web Application: Tips and Tricks

Currently, I am working on a React web application that requires the temporary storage of Torrent pieces for streaming purposes using a web player. Any recommendations on how to properly store this data temporarily in order to facilitate the streaming pro ...

Looking to include a data-* attribute within a div element for the utilization of a third-party JavaScript library like React or Next.js?

let speed = '{ "speed": 0.2 }'; <div className="section jarallax h-100vh" data-jarallax={speed} style={{backgroundImage: "url('/images/header-bg.jpg')"}} id="home"> </div> <Script src="./js/parallax.js" strate ...

Create a single JSON object by searching through two collections in MongoDB

Is it possible for you to assist me in combining data from two collections into one JSON format? Users [ user_id, user_name, city_id ] [ { "name": "Anton", "user_id": 1, "city_id": 1 }, { "name": "Vasiliy", ...

The div "tags" cannot be positioned beneath the photo as it is automatically located alongside the image inside the div

Is there a way to place the "Tags" div beneath an image, creating a bar of tags below it? I've been struggling to position it properly without disrupting the flow of the page. Using absolute positioning is not an option as it would break the layout. A ...

Encountering an error message in Material UI that reads: "Error with prop type: isValidElement is not a function" specifically while implementing the mui

Recently, I encountered a problem with MUI's Accordion component in my next.js app. It started throwing errors related to Failed prop type: isValidElement is not a function. These errors seem to be coming from various components of the MUI Accordion l ...

Locate and eliminate the item containing specific content

There are many <p> &nbsp </p> tags scattered throughout the description. I need to locate and delete any tags that contain only &nbsp. The description is enclosed in a container with the class name of desc_container. Below is an exampl ...

Is there an easy method to compare the CSS styles of a specific section in HTML?

Currently, I am facing an issue where the size of a specific area on my asp.net page changes after a post-back. It seems that the style applied to this area is being altered for some reason. This situation has raised the question in my mind - is there a m ...

Develop a customized modal using jQuery library

I have implemented a jQuery function that replaces specific words with links, however, I am looking to create a modal popup using only jQuery. Is there a way to achieve this? Below is the code snippet: $(".wpb_wrapper, p").html(function(i, html) { re ...

The parameter being passed in the JSON request is empty within the WCF Service function

I have been trying to send a list of confirmations to a server using Ajax from jQuery. However, I am facing an issue where the data is being sent but the service on the server side does not receive the list. The web method expects two parameters - a strin ...

Showing information from the data text option

I'm having trouble displaying text below the cube. The code works fine in a standalone fiddle, but it doesn't work when I incorporate it into my project. Can someone help me figure out how to show the value of data-text="Cube1"? Code t ...

The Symfony API failed to generate a response

There seems to be a problem when trying to link the Symfony API with a React application. The API is not providing any response, even though it works fine when accessed directly through the link. ApiDirectURL Fetching this data from the React app is yiel ...