1+ import { useEffect , useState } from "react" ;
2+ import "./style.css" ;
3+
4+ interface Toast {
5+ id : number ;
6+ title : string ;
7+ content : string ;
8+ }
9+
10+ const MAX_TOAST = 4 ;
11+ const INITIAL_TOASTS : Toast [ ] = Array . from ( { length : 4 } , ( _ , i ) => ( {
12+ id : i ,
13+ title : `toast - ${ i } ` ,
14+ content : "here is the content"
15+ } ) ) ;
16+
17+
18+ export default function CssToast ( ) {
19+ const [ toastList , setToastList ] = useState < Toast [ ] > ( INITIAL_TOASTS ) ;
20+ const [ index , setIndex ] = useState ( 4 ) ;
21+
22+ const addToast = ( ) => {
23+ setIndex ( index => index + 1 ) ;
24+ const toast : Toast = {
25+ id : index ,
26+ title : "toast - " + index ,
27+ content : "here is the content"
28+ } ;
29+ setToastList ( prev => [ ...prev , toast ] ) ;
30+ if ( toastList . length > MAX_TOAST ) {
31+ setToastList ( prev => prev . slice ( 1 ) ) ;
32+ } ;
33+ } ;
34+
35+ return (
36+ < div className = "css-toast-wrap" >
37+ < ul className = "toast-list" >
38+ {
39+ toastList . map ( ( toast , index ) => (
40+ < Toast key = { toast . id } index = { toastList . length - index - 1 } toast = { toast } />
41+ ) )
42+ }
43+ </ ul >
44+ < button onClick = { addToast } > Add toast</ button >
45+ </ div >
46+ )
47+ }
48+
49+ const Toast = ( { index, toast } : { index : number , toast : Toast } ) => {
50+ const [ show , setShow ] = useState ( false ) ;
51+
52+ const style = {
53+ [ "--index" as string ] : index
54+ } ;
55+
56+ useEffect ( ( ) => {
57+ setShow ( true ) ;
58+ } , [ ] ) ;
59+
60+ return (
61+ < li style = { style } className = { `${ show ? "show" : "" } ${ index >= MAX_TOAST ? "hide" : "" } ` } >
62+ < p > { toast . title } </ p >
63+ < span > { toast . content } </ span >
64+ </ li >
65+ )
66+ }
0 commit comments