Hide React micro animations on component using display:none

Is there a way to make this component appear on button click with a smooth ease-in expand or popout animation? I'd like the transition to be smoother rather than it just appearing suddenly.

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

  const handleClick = () => {
    setShow(!show);
  };

  return (
    <div>
      <Button onClick={handleClick} type="primary">
        Show Card
      </Button>
      <Card style={{ display: show && "none" }}>This is my card</Card>
    </div>
  );
};

https://codesandbox.io/s/lucid-star-fs6zi?fontsize=14&hidenavigation=1&theme=dark

Answer №1

If you want to achieve a smoother transition effect, consider using the opacity property instead of changing the display value. Here's an example implementation with the transition attribute for added animation:

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

  const handleClick = () => {
    setShow(!show);
  };

  const cardStyle = {
    opacity: show ? 0 : 1,
    transition: "all 1s ease-in"
  };

  return (
    <div>
      <Button onClick={handleClick} type="primary">
        Show Card
      </Button>
      <Card style={cardStyle}>This is my card</Card>
    </div>
  );
};

https://codesandbox.io/s/confident-morse-phg31?fontsize=14&hidenavigation=1&theme=dark

Answer №2

While the previous solution works well, I have come up with an alternative method using CSS rather than inline styles. By conditionally applying a className and managing the transition in a separate CSS file, you can achieve the desired effect. The link to the sandbox showcasing this approach is provided below.

import './CardExample.css';

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

  const handleClick = () => {
    setShow(!show);
  };

  return (
    <div className='card-example'>
      <button onClick={handleClick} type="primary">
        Show Card
      </button>
      <Card className={show ? 'showing' : 'not-showing'}>
          This is my card
      </Card>
    </div> 
  );
};

In the CSS file, you can include the following code to conditionally adjust the visibility attribute with a smooth one-second animation interval.

.not-showing {
  visibility: hidden;
  opacity: 0;
  transition: visibility 1s, opacity 0.5s linear;
}
.showing {
  visibility: visible;
  transition: visibility 1s, opacity 0.5s linear;
  opacity: 1;

}

I have set up a sandbox environment for demonstration purposes:

https://codesandbox.io/s/react-hooks-playground-boih3?fontsize=14&hidenavigation=1&theme=dark

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

In production mode, the Angular/JS Express app is stuck in an endless routing loop, while it functions perfectly in development mode

My webapp is constructed using generator-angular-fullstack. While it functions properly in development mode (grunt serve), I encounter a problem with what appears to be an endless routing loop when switching to production mode (grunt serve:dist). The outp ...

How can I filter an array to retain only the initial 5 characters of every element?

I need help using the .map function to transform this array so that only the first 5 characters are displayed, like "01:00", "02:00"? This is the array: ["01:00:00 AM", "02:00:00 AM", "03:00:00 AM", "04:00:00 AM", "05:00:00 AM", "06:00:00 AM", "07:00:00 ...

Should I include all components in the app.js file or import them directly into the Vue component?

Now I am faced with two options for injecting my component into my application. The first method is in app.js Vue.component( "notice-master-component", require("./components/site/communication/Notice/MasterComponent.vue") ); In any Vue ...

What is the best way to continuously loop an image from left to right and right to left indefinitely using JavaScript?

As part of the challenge, I am tasked with creating a Pacman game using HTML, CSS, and JavaScript. One key aspect is to control the movement of the ghosts throughout the game. However, I am facing an issue with the current function that controls the ghost& ...

Discovering vacation days in the Persian calendar (Shamsi)

How can I access Persian calendar holidays in React without using paid APIs? Is there a free way to get information about Persian (shamsi) holidays, including descriptions? { 1402:[ { date: "1402/1/2", description: "عیدن ...

CSS - Problem with image display and hover functionality

I am facing an issue with hover effect on an image. The hover works fine but the original image remains visible above the hovered image. I have attempted to use z-index to fix this problem without success. Below is the CSS code: #login, #logout { fl ...

Suggestions for deleting browser cache programmatically by utilizing JS or HTML

Having trouble clearing the Chrome browser cache using Add-ons. Working on a site development project using JSP with Java, it's crucial for security reasons to clear the cache. Tried multiple methods but none have been successful. Any suggestions? Ple ...

Node-zookeeper-client executes the callback for getData method only one time

I have been using node-zookeeper-client in my Node.js server. Everything works smoothly when I watch a znode data with the getData method for the first time. However, I encounter an issue when updating the node (using the ZK-Web user interface) - the wat ...

"Encountering issues while upgrading Polymer project version from 0.5 to 1.0

I am in the process of upgrading my project from polymer .5 to polymer 1.0. After installing the new version of the polymer library, iron element, and paper element, I encountered the following error: polymer-micro.html:63 Uncaught TypeError: prototype ...

Pass information from Vue JS v-for to a button when it is clicked

Just started learning Vue JS and encountered a small issue I'm currently looping through an array with a button inside the div I'm iterating over The goal is to grab the data of the selected item after clicking on the button For example, suppo ...

Troubleshooting issue with the inability to terminate Electron JS child processes

I have developed an Electron JS script to execute a .exe file. The concept is that when the 'start' button is clicked, the .exe should start as a child process, and when the 'stop' button is clicked, the child process should be terminat ...

Tips for incorporating external JavaScript code into React components

I have been tasked with integrating a graphical widget into a React component for a project I am working on. The widget_api code provided by RIPE Stat is required to accomplish this. Previously, in HTML5, the integration was successful using the following ...

Executing various tasks during the mongodb update process: utilizing $addToSet, $inc, and performing aggregations such as $subtract

As I delve into learning how to use mongodb, I encountered a challenge when attempting to execute multiple operations in a single update query. Specifically, I encountered an error related to the $addToSet method. Code: function insertBook(db, title, aut ...

Error message: Redux-toolkit: The store does not contain a valid reducer

I've hit a roadblock with understanding how to integrate redux and next.js. Despite spending countless hours trying to connect the two, I keep encountering an error stating "TypeError: Cannot read property 'getState' of undefined". It seems ...

What could be causing the "no such file" error to occur while attempting to use the "mammoth" tool to convert a basic .docx file?

Here is my code snippet. The file contains a basic "hello world" and I have the hello.docx file located in the same directory where I am running this mammoth function. Error message: fatal Error: ENOENT: no such file or directory, open './hello.docx& ...

Error in Compass Compilation when encountering Unicode Characters

After compiling with Compass, I noticed that if I don't include @charset "UTF-8"; in my root scss file, the output looks like this: @charset "IBM437"; Even though my CSS output still displays the correct Unicode characters, such as: content: "ĐĂN ...

Electron experiences a crash while attempting to execute an HTTPS request within an addeventlistener callback function

In the process of creating a simple Electron application that facilitates user login into a system, I encounter an issue. The app collects the username and password entered by the user through form text inputs. Upon clicking the "login" button, the program ...

Error: Unable to assign the value of 'setState' property to an object that is not defined. React

After retrieving data from the NYTimes API and logging it to the console, I noticed that my initial state was set as {searchResponse: null}. However, when attempting to set the state with the response using this.setState=({searchResponse:response.data}); a ...

Navigating through hashed URLs with a Flexslider component

I have a website under construction that utilizes a flexslider, and I am looking to incorporate URL hash navigation. My goal is to extract the slide index based on the URL hash. I have examined the code for manual navigation where the index of the clicked ...

Totally at a standstill. (Problem with MongoDB in my MERN stack)

Currently developing an app, focusing on a feature that takes user input and stores it in the database. Although I've implemented this in past projects, I'm facing a persistent issue. Upon user input submission, the data is sent to the backend w ...