Skip to content

Instantly share code, notes, and snippets.

@meysam81
Created March 31, 2024 08:12
Show Gist options
  • Save meysam81/7495a8e7724066fcd597681e74416df3 to your computer and use it in GitHub Desktop.
Save meysam81/7495a8e7724066fcd597681e74416df3 to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from 'react';
import styles from './MotdForm.module.css';
const MotdForm = () => {
const [motd, setMotd] = useState('');
const [isEditing, setIsEditing] = useState(false);
const MOTD_EXPIRATION_KEY = 'motdExpiration';
const MOTD_KEY = 'motd';
useEffect(() => {
const savedMotd = localStorage.getItem(MOTD_KEY);
const expiration = localStorage.getItem(MOTD_EXPIRATION_KEY);
if (savedMotd && !isExpired(expiration)) {
setMotd(savedMotd);
setIsEditing(false);
} else {
clearMotd();
}
}, []);
const handleInputChange = (e) => {
setMotd(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
localStorage.setItem(MOTD_KEY, motd);
const expiration = getTomorrowDate();
localStorage.setItem(MOTD_EXPIRATION_KEY, expiration);
setIsEditing(false);
};
const handleDoubleClick = () => {
setIsEditing(true);
};
const clearMotd = () => {
localStorage.removeItem(MOTD_KEY);
localStorage.removeItem(MOTD_EXPIRATION_KEY);
setMotd('');
setIsEditing(false);
};
const isExpired = (expiration) => {
const now = new Date();
const expireDate = new Date(expiration);
return now >= expireDate;
};
const getTomorrowDate = () => {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
return tomorrow.toISOString();
};
return (
<div className={styles.container}>
<div className={styles['motd-form-container']}>
{isEditing ? (
<form onSubmit={handleSubmit} className={styles.form}>
<input
type="text"
value={motd}
onChange={handleInputChange}
autoFocus
className={styles.input}
/>
<button type="submit" className={styles.button}>Save</button>
<button type="button" onClick={clearMotd} className={styles.button}>
Clear
</button>
</form>
) : (
<div
onDoubleClick={handleDoubleClick}
className={styles.motdText}
>
{motd ? (
<h2>{motd}</h2>
) : (
<p>Double click here to set your Message of the Day</p>
)}
</div>
)}
</div>
</div>
);
};
export default MotdForm;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment