Animating toggled classes in React can be achieved by utilizing keyframe animations or

I am looking to implement a simple transition/animation using React and CSS. The concept is to have an image that, when clicked, toggles a new section below with a nice transition effect.

This is my React code:

const [show, setShow] = useState(false);

 <div className="box" id="box" onClick={() => setShow(!show)}>
      <img src="myImage" />
 </div>

Here's the section that toggles:

{show && (
          <div className="transform popup">This text will show!</div>
)}

The toggle functionality works perfectly fine, but the animation does not.

Below is the CSS for the animation:

.popup {
    height: 0px;
    width: 0px;
}

.transform {
    -webkit-transition: all 2s ease;
    -moz-transition: all 2s ease;
    -o-transition: all 2s ease;
    -ms-transition: all 2s ease;
    transition: all 2s ease;
}

.transform-active {
    background-color: #45cee0;
    height: 200px;
    width: 200px;
}

In jQuery, I would typically use something like this:

$("#box").click(function() {
  $('.transform').toggleClass('transform-active');
});

How can I adapt this into React-friendly code?

Answer №1

I have implemented @keyframes in my CSS animation and it seems to be working perfectly. :)

// React component
const [boxVisibility, setBoxVisibility] = useState(false);

const showNewBox = () => {
    setBoxVisibility(!boxVisibility)
}

return(
    <div>
        <button type="button" onClick={() => showNewBox()}>Edit</button>
        {boxVisibility && <div className="show-box">
            <q>I am the new guy</q>
        </div>}
    </div>

);

// Custom CSS for animations
@-webkit-keyframes SHOW-BOX {
    0%   { opacity: 0; }
    100% { opacity: 1; }
}
@-moz-keyframes SHOW-BOX {
    0%   { opacity: 0; }
    100% { opacity: 1; }
}
@-o-keyframes SHOW-BOX {
    0%   { opacity: 0; }
    100% { opacity: 1; }
}
@keyframes SHOW-BOX {
    0%   { opacity: 0; }
    100% { opacity: 1; }
}

.show-box {
    -webkit-animation: SHOW-BOX 2s ease;
    -moz-animation: SHOW-BOX 2s ease;
    -o-animation: SHOW-BOX 2s ease;
    animation: SHOW-BOX 2s ease;
}

Answer №2

If you want to maintain the visibility of your div while toggling classes with jQuery, consider setting initial width and height to zero and just toggle the desired class as shown below:

    <div className={`toggle popup ${visible ? 'active-toggle' : ''}`}>
        Display this content!
    </div>

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

I aim to retrieve the value of the input textbox located alongside the button using jQuery

Can you help me figure out how to retrieve the value from an input box that is next to a button? Here is the HTML code: <span> <input type="text" value="{{p.filename}}" id="file_{{p.id}}" size=60 onclick="copy_for_file_name({{p.id}}) ...

Adjusting the navigation image as it passes through various div elements during scrolling

Is it possible to dynamically change an image in the navigation bar based on the user's scroll position? For example, I want pic1 to be displayed when the page content is at the top, then switch to pic2 once the user reaches the footer, and then back ...

The utility of commander.js demonstrated in a straightforward example: utilizing a single file argument

Many developers rely on the commander npm package for command-line parsing. I am considering using it as well due to its advanced functionality, such as commands, help, and option flags. For my initial program version, I only require commander to parse ar ...

What is the recommended approach for managing state in React when multiple components are trying to access and modify its data at the same time?

Issue: I am experiencing difficulty in adding new keys and/or values to the JSON editor or YAML editor when they both share and update the same state. The parent component sends JSON data to the child component through props import * as React from 'r ...

Encountering issues with Firebase data loading after refreshing the web browser

Greetings to all readers. I am facing a challenge with using React, Redux, and Firebase together. I have successfully set the Firebase data in the React store using Redux. The data is then passed to the component using mapStateToProps. However, whenever I ...

Accessing cell values within a table using JavaScript

I am having some trouble with extracting unique IDs from the input text areas in the first column of an HTML table. These IDs are dynamically assigned using JavaScript. Can someone help me with this issue? Below is the HTML code for my table: <table id ...

Exploring the function.caller in Node.js

Currently, I have a task that relies on function.caller to verify the authorization of a caller. After reviewing this webpage, it seems that caller is compatible with all major browsers and my unit tests are successful: https://developer.mozilla.org/en-U ...

Is there a way for me to retrieve the name and extension of an attached file in an input field of type "text"?

Could you assist me with a task? I have a table and I would like to extract the name and extension of each file and insert it into an input field below each "file" type input. This information will then be saved into a MySQL database, allowing me to create ...

Exploring the versatility of Bootstrap and JQuery's draggable feature

I am currently working on a website that will enable users to search through a list of courses. Once a course is chosen from a typeahead search, it will be added to a basket. Users can then drag and drop the selected courses into one of four semesters disp ...

Create a PDF document with a custom header and footer by converting an HTML template using itext7

I attempted to utilize the following HTML template in an effort to convert it to a PDF using iText7, however, I am facing an issue where both the header and footer are not aligning to their designated positions. You can view the example I used here. I am s ...

Can you identify the date stored in this JSON object?

I need to analyze some JSON data This is the specific snippet required for my query. "UpdatedDate":"\/Date(1311377875937)\/" I'm unsure about that number, but the updated date indicates when the item was last modified Moreover, how can I ...

Incorporate sweetalert2 into your node.js and express.js project

Trying to incorporate sweetalert2 into my Node.js and Express.js project has not been successful so far. The error message I keep encountering is: swal is not defined ReferenceError: swal is not defined Here are my configurations index.js var express ...

What is the procedure for collapsing a table row or grid?

Looking at this image, I'm trying to find a way to collapse the breakfast row. Any ideas on how I can collapse either the entire tr or with a div? ...

Tallying the number of iterations a loop undergoes

I have been tasked with developing a dice game where the player places a bet amount and rolls the dice until they run out of money. My goal is to track the number of times the dice has been rolled before the player goes broke, and store this data in an a ...

React JS: Component failing to render

My react component is not rendering and I can't find any bugs. The problem arises when I set the isLoggedIn state to "true", resulting in my HeroSlide not rendering If isLoggedin = false, then: https://i.sstatic.net/JoDSn.jpg If isLoggedIn = true, t ...

html tables cannot be aligned row by row

I am attempting to display messages row by row and then show a text box for input to send a message. The issue I am facing is that I can display the messages row by row, but the text box appears next to the displayed messages horizontally rather than at th ...

How to Achieve Seamless Vertical Scrolling Through Clicking a Button

I'm currently working with Bootstrap 4 Modal and have removed the Overflow-Y (ScrollBar) to enhance the design. However, I've also incorporated a function with two buttons (Up & Down) using JavaScript to facilitate easier navigation for users. Th ...

Is the order of state variables important in React components?

Upon executing the code below, an error "Cannot read properties of null (reading 'login')" occurs, triggered by reaching the return statement at the end. This error persists despite the presence of checks for the boolean before the return stateme ...

Tips for developing a sophisticated HTML quiz

I have spent countless hours perfecting this quiz. I have successfully created a quiz that reveals solutions at the end, but I want to take it one step further. I envision the answers appearing after each incorrect response from the user, and no answer sho ...

JavaScript for Designing in Two and Three Dimensions

I need to take a 2D design created in microstation and display it on the web using a tool like javascript, Unity 3D, or another similar option. The web tool should have basic functionality like reshaping or adding new shapes. My current approach involves c ...