Home > OS >  How can i make all elements dissapear when one element is shown in react js?
How can i make all elements dissapear when one element is shown in react js?

Time:06-16

I make a countdown application. There always has to be shown one countdown, by default countdown till New Year. I also have buttons for each subject of countdown. But i want, when one button is clicked that that countdown is shown and the countdown that was shown before has to dissapear. How can i make that dissapear when another is shown?

App.js

import './App.css';
import React from "react";
import NewYear from './Components/NewYear';
import Chinese from './Components/Chinese';
import Birthday from './Components/Birthday';
import {useState} from 'react';

function App() {
  const [isShown, setIsShown] = useState(true);
  const [isShown2, setIsShown2] = useState(false);
  const [isShown3, setIsShown3] = useState(false);

  const handleClick = event => {
    setIsShown(current => !current);
  };
  const handleClick2 = event => {
    setIsShown2(current => !current);
  };
  const handleClick3 = event => {
    setIsShown3(current => !current);
  };

  return (
    <div className="App">
      {isShown && (<NewYear/>)}  
      {isShown2 && (<Chinese/>)}  
      {isShown3 && (<Birthday />)}  
      <button onClick={handleClick} className='nieuw'>New Year</button>
      <button onClick={handleClick2} className='chinees'>Chinese New Year</button>
      <button onClick={handleClick3} className='verjaardag'>My Birthday</button>
    </div>
  );
  };

export default App;

Component

import React, {useEffect, useState} from "react";
import './styles.css';

function NewYear() {
    const calculateTimeLeft = () => {
        let year = new Date().getFullYear();
    
        const difference =  new Date(`01/01/${year 1}`) -  new Date();
        
        let timeLeft = {};
    
        if (difference > 0) {
          timeLeft = {
            days: Math.floor(difference / (1000 * 60 * 60 * 24)),
            hours: Math.floor((difference / (1000 * 60 * 60)) % 24), 
            minutes: Math.floor((difference / 1000 / 60) % 60),
            seconds: Math.floor((difference / 1000) % 60)
          };
        }
    
        return timeLeft
      };
        
        const [timeLeft, setTimeLeft] = useState(calculateTimeLeft());
        const [year] = useState(new Date().getFullYear());
    
        useEffect(() => {
          const timer = setTimeout(() => {
            setTimeLeft(calculateTimeLeft());
          }, 1000);
          return () => clearTimeout(timer);
        });
        const timerComponents = [];
    
      Object.keys(timeLeft).forEach((interval) => {
        if (!timeLeft[interval]) {
          return;
      }
    
      timerComponents.push(
        <span>
          {timeLeft[interval]} {interval}{" "}
        </span>
      );
      });
      return (
        <div className="nieuwjaar">
          <h1>New Year {year 1} Countdown</h1>
          {timerComponents.length ? timerComponents : <span>Time's up!</span>}
        </div>
      );
}

export default NewYear;

CodePudding user response:

Here's an approach, instead of using separate boolean state values for each count down timer, you can keep track of the active one.

function App() {
    const [activeCountDown, setActiveCountDown] = useState('NewYear');

    const handleCountDownClick = (counterId) => () => setActiveCountDown(counterId);

    const getActiveCountDown = () => {
        switch (activeCountDown) {
            case 'ChineseNewYear':
                return <Chinese />;
            case 'Birthday':
                return <Birthday />;
            case 'NewYear':
                return <NewYear />;
            default:
                return null;
        }
    };

    return (
        <div className='App'>
            {getActiveCountDown()}
            <button onClick={handleCountDownClick('NewYear')} className='nieuw'>
                New Year
            </button>
            <button onClick={handleCountDownClick('ChineseNewYear')} className='chinees'>
                Chinese New Year
            </button>
            <button onClick={handleCountDownClick('Birthday')} className='verjaardag'>
                My Birthday
            </button>
        </div>
    );
}
  • Related