Automatically conceal a div or flash message after a short period of time by utilizing CSS3 in a React

I am relatively new to the React environment and recently created a basic component for a bookmarking feature.

Essentially, when the favourite icon is clicked,

an ajax call is sent > a record is created in the database > on ajax success, a flash message displays "Page added to favourites."

It's a toggle button, so clicking on it again will,

send another ajax call > delete the record in the database > show a flash message on successful deletion "Page removed from favourites."

Here is the component I wrote, which functions perfectly. However, I am not fond of using the setTimeout function to hide the flash message. I believe there may be an alternative way (possibly using CSS) to achieve the same result in a more React-oriented manner.

import React, {
  PropTypes
} from 'react';
import {
  Component
} from 'aplus-base';
import axios from 'axios';

const API = "http://localhost:3000/favourites/toggle"
const API2 = "http://localhost:3000/favourites/current_bookmark_status"

@Component
export default class Bookmark extends React.Component {
  static styles = require('./bookmark.sass')

  state = {
    bookmarked: '',
    message: "",
    alert: false
  }

  componentDidMount() {
    this.fetchData();
  }

  toggle() {
    const querystring = require('querystring')
    axios.post(API, querystring.stringify({
        current_page_key: '/marketing'
      }), {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        }
      })
      .then(response => {
        this.setState({
          bookmarked: response.data.bookmarked,
          alert: true
        });
        const message = response.data.bookmarked ? "Added to Favourites" : "Removed from Favourites"
        this.setState({
          message
        })
        setTimeout(() => {
          this.setState({
            alert: false
          });
        }, 2000);
      })

  }
  fetchData = () => {
    const querystring = require('querystring')
    axios.post(API2, querystring.stringify({
        current_page_key: '/marketing'
      }), {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        }
      })
      .then(response => {
        this.setState({
          bookmarked: response.data.bookmarked
        });
      })
  }

  render() {
    return ( <
      div >
      <
      i className = {
        this.state.bookmarked ? "icon icon-bookmarked" : "icon icon-bookmark"
      }
      onClick = {
        this.toggle.bind(this)
      }
      /> <
      div styleName = {
        `result ${this.state.alert ? "alert-shown": "alert-hidden"}`
      } > {
        this.state.message
      } <
      /div>     <
      /div>
    )
  }
}
.icon display: inline-block width: 30px height: 30px background: no-repeat center background-size: contain vertical-align: middle &.icon-bookmark background-image: url(../assets/bookmark.png) transition: all 1s linear &.icon-bookmarked background-image: url(../assets/bookmarked.png) transition: all 1s linear .result position: fixed top: 0 left: 40% width: 20% box-sizing: border-box padding: 4px text-align: center font-weight: bold .alert-shown opacity: 1;
transition: all 250ms linear;
.alert-hidden opacity: 0;
transition: all 250ms linear;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Answer №1

To hide your element after a certain time, you can utilize CSS3 animations. Without being able to test your code output myself, I cannot provide the exact snippet for you. However, one way to achieve this is by adding classes dynamically upon request success. You can use the same method you are currently using or consider using a npm package like "classnames" to apply animations for showing and fading your element.

For instance, you can implement the following animation:

animation: FadeAnimation 1s ease-in .2s forwards;

In this example, the FadeAnimation will run for 1 second with an ease-in effect, starting 0.2 seconds after the class is attached.

@keyframes FadeAnimation {
  0% {
    opacity: 1;
    visibility: visible;
  }

  100% {
    opacity: 0;
    visibility: hidden;
  }
}

This keyframe rule will transition the element from a visible state to a hidden state. By incorporating additional properties at different percentage points, you can introduce intermediate stages in your animation sequence. This approach can also be applied for removing elements.

For more information on CSS3 Animations, refer to W3Schools' guide.

Answer №2

I came across a challenge where I needed to create an overlay using React and hide it with CSS after a brief period of time. Thankfully, I stumbled upon this question and found the solution provided by @jefree-sujit incredibly helpful.

The final outcome involves initially displaying a hidden overlay, transitioning its visibility through a CSS animation, and then concealing it once again.

Within my render method, I implemented my component like so:

{isPostFulfilled && <SuccessDisplay />}

(Note: The implementation may vary based on how API calls are handled. In my case, I utilize react-redux-fetch to manage pending/fulfilled/rejected states for my calls.)

The SuccessDisplay component utilizes styled-components to act as the overlay:

// @flow
import React from 'react';
import styled from 'styled-components';
import { BootstrapIcon } from 'skin';

export const Styling = styled.div`
  .success {
    animation: hide-animation 0.6s ease-in 0s;
    visibility: hidden;
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100vh;
    width: 100vw;
    background-color: rgba(0, 0, 0, 0.3);
    z-index: 100000;

    .ok-icon {
      font-size: 50px;
      cursor: default;
      opacity: 0.9;
      position: absolute;
      top: 48%;
      left: 48%;
      color: green;
      margin: 0 auto;
    }

    @keyframes hide-animation {
      0% {
        opacity: 1;
        visibility: visible;
      }

      100% {
        opacity: 0;
        visibility: hidden;
      }
    }
  }
`;

const SuccessDisplay = () => (
  <Styling>
    <div className="success">
      <BootstrapIcon icon="ok" className="ok-icon" />
    </div>
  </Styling>
);

export default SuccessDisplay;

The BootstrapIcon component is utilized to render glyphicons from react-bootstrap.

The key aspect of the animation in the CSS snippet is that: it triggers the hide-animation lasting for 0.6 seconds, utilizing the ease-in transition style within that duration, beginning instantly (0 seconds) after loading the styles.

It's crucial to include visibility: hidden in the initial styles as well, as the starting point and endpoint of the animation. Once the animation concludes (after 0.6 seconds), the styles revert back to their original state.

I hope this explanation proves useful to someone facing a similar issue in the future!

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

Invoke the designated JavaScript function within a subordinate <frame>

Below is an example of the standard HTML structure for a parent page named "index.html": <html> <head> <title>test title</title> </head> <frameset cols="150,*"> <frame name="left" src="testleft.html"> ...

Exploring the Google Plus API: Discover individuals who are following a specific individual

Has anyone managed to successfully extract a list of individuals who have included a specific user in their circles or are following them on social media platforms? I am currently using the official JS Library for this task, but any solution in any progr ...

What could be causing the undefined value for this.props.username in React-Redux?

I'm facing an issue when trying to access this.props.username in the following code snippet: loginClick = (event) => { event.preventDefault(); console.log('Login submit click, props.username: ' + this.props.username); this.props.lo ...

Having trouble retrieving all JSON properties

I am facing an issue with my json structure where I am unable to access certain properties. I can only access the main properties like type, properties, and so on within that hierarchy level. However, I cannot seem to access icon, iconURL, or title. The da ...

Fetching data from ExpressionEngine using AJAX

Looking to display ExpressionEngine entries in a popup modal using jQuery and ajax. When the user clicks on an entry title, the full entry should be displayed in the modal. Additionally, next and previous buttons within the modal are desired for navigation ...

Disabling eslint does not prevent errors from occurring for the unicorn/filename-case rule

I have a file called payment-shipping.tsx and eslint is throwing an error Filename is not in camel case. Rename it to 'paymentShipping.tsx' unicorn/filename-case However, the file needs to be in kebab case since it's a next.js page that s ...

Error when parsing JSON due to the presence of backslashes within the serialized object

When trying to call a server side function and parse the response in client side using JavaScript and Ajax, I encountered a parse error. It seems that the issue lies with the backslash that the JavaScriptSerializer adds to serialize the object. The respons ...

Error encounter when loading the chunk for FusionCharts's overlappedbar2d.js in React.js: fusioncharts.overlapped

Currently, I am working on a web application that utilizes next.js and FusionCharts. Within the app, various FusionChart types have already been set up. My task now is to integrate the Overlapping Bars chart as outlined in the following documentation: How ...

Incorporating a React element into a JavaScript object's property: A comprehensive guide

Below is a React Element named Info that has been attached to a Javascript object named myObj: let Info = ( <Info type="green" /> ); let myObj = { ReactComp: Info }; Now, the goal is to render the Info component using the above myObj objec ...

"Exploring the best way to loop through multiple JSON data in a jQuery response

https://i.stack.imgur.com/O0F6g.pngMy JSON response contains multiple data points presented as follows. WellNames […] 0 {…} id 56 well_name AL HALL api 34005205550000 1 {…} id 498 well_name BONTRAGER api 34005233850000 2 {…} id 499 ...

Unable to reset iframe style height in IE8 using JavaScript

I am encountering an issue with resetting the height of an iframe using JavaScript. Here is the code snippet I am working with: var urlpxExt = document.getElementById('urlPx'); urlpxExt.style.height = "200px"; While this approach works well in m ...

Extra spaces within the source code visible after the page has been processed by Angular

Within my angular application, I am retrieving a list of addresses from a service that provides an object structured like this: { Flat: "10B", BuildingName: "Some Building", Line: "10B Some Building Road Town POST CODE", Postcode: "POST CODE", ...

Learn how to collapse a collapsible section in Jquery Mobile by clicking on a link. Check out the example on JSFiddle

Is there a way to make the data-role collapsible collapse when clicking a tab link? I've tried using an on-click function without success. Any ideas or alternative solutions? Thanks. Check out my JSFiddle, where you can see that the tabs change but t ...

When validated, the Yup.date() function seamlessly converts a date into a string without including the timezone

Currently, I am integrating Yup with react-hook-form and have defined the following schema in Yup: const validationSchema = Yup.object({ installation: Yup.string().nullable().required("Required"), from_date: Yup.date() .max(new Date(), "Can ...

Using JQuery, you can make a $.get or $.ajax request to a PHP script on the server that needs to receive

A PHP function called functionexchangeRate($exchangeFrom, $exchangeTo) has been created with two parameters in mind. However, I am currently struggling to properly call this PHP script using Jquery's $.get function because I can't seem to figure ...

Displaying the product price in a component header in Next.js when clicking on the product

I am relatively new to Next.js (React) and facing a challenge. I have created two components, header.tsx and product.tsx. These are being called in the file stepperLine.tsx under the "components" folder. My goal is to display the price of the product in th ...

Creating Custom Filters in Angular using Functions

Attempting to filter ng-repeat using a function instead of an actual filter has presented some challenges. The code snippet below demonstrates the attempt: <tr ng-repeat="(key, value) in dataObj| filter:dataFilter"> The intention is to define dataF ...

Utilizing JavaScript functions alongside a button within a Handlebars template

My handlebars project has the following structure: Project | +-- server.js +-- package.json +-- package-lock.json | +-- public | | | |-- css | | | + -- style.css | +-- views | | | |-- layouts | | | | | + -- main. ...

Using React.js to select and change the color of an element

I'm developing a movie theater app, in which I am building a feature to select seats in the cinema hall and add them to the cart. Here is the function that displays the cinema hall: export default function CinemaHall(props) { const row = props.row ...

Unable to stop page refresh following form submission or file upload

Is it possible to upload a photo with Ajax to Express and have the response generate desired HTML? Whenever I submit the form, it redirects me and displays the picture data as an object. Here's the Express code: const storage = multer.diskStorage({ ...