При завершения Event (События), фон события не перерисовывается

Рейтинг: 1Ответов: 1Опубликовано: 27.05.2023

Всем здравствуйте. Никак не могу понять, что не так. При создании события появляется данный фон #EF5350, а когда фон завершается, то фон становится #18FFFF. А должно быть наоборот, почему так получается? Вроде все проверил. Ниже прикрепил сам код и стили к нему.

import React, { useRef, useEffect, useState } from "react";
import styles from './EventItem.module.sass';
import moment from 'moment';
import { toast } from 'react-toastify';

const EventItem = (props) => {
    const {
        eventName,
        eventStart,
        eventEnd,
        eventNotification,
        eventId,
        userId,
        updateEvents } = props;

    const [editing, setEditing] = useState(false);
    const [editedName, setEditedName] = useState(eventName);
    const [editedStart, setEditedStart] = useState(eventStart);
    const [editedEnd, setEditedEnd] = useState(eventEnd);
    const [completed, setCompleted] = useState(false);

    const ref = useRef(); 

    const turnOnNotification = () => {
        console.log(`turn on notification`)
          ref.current.classList.add(styles.notification);
          toast.error(`The ${eventName} event will end soon!`);
      };

    const deleteEvent = () => {
        const userEvents = JSON.parse(localStorage.getItem(`${userId}`));
        const index = userEvents.findIndex(event => event.eventId === eventId);
        if (index >= 0) {
            userEvents.splice(index, 1);
            localStorage.setItem(`${userId}`, JSON.stringify(userEvents));
        }
        updateEvents();
    }

    const startEditing = () => {
        setEditing(true);
    }

    const cancelEditing = () => {
        setEditing(false);
        setEditedName(eventName);
        setEditedStart(eventStart);
    }

    const saveEditing = () => {
        const userEvents = JSON.parse(localStorage.getItem(`${userId}`));
        const index = userEvents.findIndex(event => event.eventId === eventId);
        if (index >= 0) {
            userEvents[index].eventName = editedName;
            userEvents[index].eventStart = editedStart;
            localStorage.setItem(`${userId}`, JSON.stringify(userEvents));
        }
        setEditing(false);
        updateEvents();
    }

    useEffect(() => {
        const isEventCompleted = moment(eventEnd).isBefore(moment());
        setCompleted(isEventCompleted);
      
        if (isEventCompleted) {
          turnOnNotification();
        }
      
        const diffNotification = moment(eventNotification).diff(moment());
        const timerNotification = setTimeout(turnOnNotification, diffNotification);
      
        return () => {
          clearTimeout(timerNotification);
        };
      }, [eventEnd, eventNotification]);

    return (    
        <>
            <li
                ref={ref}
                className={`${styles.container} ${completed ? styles.completed : ""} ${
                    editing ? styles.editing : ""
                }`}
                >
                <div className={styles.eventBody}>
                    {editing ? (
                        <>
                            <input
                                type="text"
                                value={editedName}
                                onChange={(e) => setEditedName(e.target.value)}
                                className={styles.eventTitle}
                            />
                            <input
                                type="datetime-local"
                                value={moment(editedStart).format("YYYY-MM-DDTHH:mm")}
                                onChange={(e) => setEditedStart(e.target.value)}
                                className={styles.eventStart}
                            />
                            <input
                                type="datetime-local"
                                value={moment(editedEnd).format("YYYY-MM-DDTHH:mm")}
                                onChange={(e) => setEditedEnd(e.target.value)}
                                className={styles.eventEnd}
                            />
                        </>
                    ) : (
                        <>
                            <div className={styles.eventTitle}>{eventName}</div>
                            <span>{moment(eventStart).format('DD MMM YYYY HH:mm')}</span>
                            {' '}
                            <span>{moment(eventEnd).format('DD MMM YYYY HH:mm')}</span>
                        </>
                    )}
                </div>
                <div className={styles.actions}>
                    {editing ? (
                        <>
                            <i onClick={saveEditing} className={`fas fa-solid fa-save ${styles.saveIcon}`}></i>
                            <i onClick={cancelEditing} className={`fas fa-solid fa-times ${styles.cancelIcon}`}></i>
                        </>
                    ) : (
                        <i onClick={startEditing} className={`fas fa-solid fa-edit ${styles.editIcon}`}></i>
                    )}
                    <i onClick={deleteEvent} className={`fas fa-solid fa-trash ${styles.deleteIcon}`}></i>
                </div>
            </li>
        </>
    );
}

export default EventItem;
.notification 
  background-color: #18FFFF!important
  border-radius: 5px
  color: black

.container
    display: flex
    align-items: center
    justify-content: space-between
    background-color: #18FFFF
    padding: 20px
    margin-bottom: 15px
    border-radius: 5px

    @media(max-width: 400px)
        flex-direction: column

    &:hover
        background-color: #E0E0E0!important   

    &.completed 
    background-color: #EF5350
    color: black

.eventBody
    width: 100%

    @media (max-width: 630px)
        min-width: 200px

    .eventTitle
        color: #006064
        font-size: 18px
        font-weight: 500
        margin-right: 20px

    span
        font-size: 13px
        color: #0277BD
        padding-top: 15px
        display: flex
        margin: -1em
        margin-left: 0em
        margin-top: -3px

.actions
    display: flex

    .editIcon
        color: blue
        font-size: 25px    
        cursor: pointer 
        margin-right: 15px

    .saveIcon   
        color: #7B1FA2
        font-size: 25px    
        cursor: pointer 
        margin-right: 15px

    .cancelIcon
        color: #E91E63
        font-size: 25px    
        cursor: pointer 
        margin-right: 15px

    .deleteIcon
        color: red
        font-size: 25px    
        cursor: pointer 

Ответы

▲ 0

Вот как должен выглядеть стиль для завершенных событий:

&.completed {
    background-color: #18FFFF;
    color: black;
}

А вот стиль для незавершенных событий:

.container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #EF5350;
    padding: 20px;
    margin-bottom: 15px;
    border-radius: 5px;

    @media(max-width: 400px) {
        flex-direction: column;
    }

    &:hover {
        background-color: #E0E0E0!important;
    }
}

Надеюсь, это поможет вам решить проблему!