@@ -5,42 +5,42 @@ import NestedStickyDemo from './NestedStickyDemo';
55import DynamicStickyDemo from './DynamicStickyDemo' ;
66
77const pages = [
8- { name : 'iPhone Contacts Demo' , component : < ContactListDemo /> } ,
9- { name : 'Mixed Sticky Modes Demo' , component : < MixedModeDemo /> } ,
10- { name : 'Nested Sticky Containers' , component : < NestedStickyDemo /> } ,
11- { name : 'Dynamic Sticky Items' , component : < DynamicStickyDemo /> } ,
8+ { hash : 'ios-contact' , name : 'iPhone Contacts Demo' , component : < ContactListDemo /> } ,
9+ { hash : 'mixed-mode' , name : 'Mixed Sticky Modes Demo' , component : < MixedModeDemo /> } ,
10+ { hash : 'nested' , name : 'Nested Sticky Containers' , component : < NestedStickyDemo /> } ,
11+ { hash : 'dynamic' , name : 'Dynamic Sticky Items' , component : < DynamicStickyDemo /> } ,
1212] ;
1313
1414// Sync pageIdx with location.hash
15- function getIdxFromHash ( pagesLen : number ) {
16- const idx = Number ( window . location . hash . replace ( '#' , '' ) ) ;
17- return Number . isFinite ( idx ) && idx >= 0 && idx < pagesLen ? idx : 0 ;
15+ function getPageHashFromLocation ( ) {
16+ const hash = window . location . hash . replace ( '#' , '' ) ;
17+ return pages . find ( p => p . hash === hash ) ? hash : pages [ 0 ] . hash ;
1818}
1919
2020export default function App ( ) {
21- const [ pageIdx , setPageIdx ] = useState ( ( ) => getIdxFromHash ( pages . length ) ) ;
21+ const [ pageHash , setPageHash ] = useState ( ( ) => getPageHashFromLocation ( ) ) ;
2222
2323 useEffect ( ( ) => {
24- const onHashChange = ( ) => setPageIdx ( getIdxFromHash ( pages . length ) ) ;
24+ const onHashChange = ( ) => setPageHash ( getPageHashFromLocation ( ) ) ;
2525 window . addEventListener ( 'hashchange' , onHashChange ) ;
2626 return ( ) => window . removeEventListener ( 'hashchange' , onHashChange ) ;
2727 } , [ ] ) ;
2828
29- const handleNav = ( i : number ) => {
30- window . location . hash = String ( i ) ;
31- setPageIdx ( i ) ;
29+ const handleNav = ( n : string ) => {
30+ window . location . hash = n
31+ setPageHash ( n ) ;
3232 } ;
3333
3434 return (
3535 < div style = { { minHeight : '100vh' , background : '#f7f7f7' } } >
3636 < nav style = { { display : 'flex' , gap : 16 , padding : 16 , background : '#fff' , borderBottom : '1px solid #eee' } } >
37- { pages . map ( ( p , i ) => (
38- < button key = { p . name } onClick = { ( ) => handleNav ( i ) } style = { { fontWeight : pageIdx === i ? 'bold' : undefined } } >
37+ { pages . map ( ( p ) => (
38+ < button key = { p . hash } onClick = { ( ) => handleNav ( p . hash ) } style = { { fontWeight : pageHash === p . hash ? 'bold' : undefined } } >
3939 { p . name }
4040 </ button >
4141 ) ) }
4242 </ nav >
43- < div style = { { padding : 16 } } > { pages [ pageIdx ] . component } </ div >
43+ < div style = { { padding : 16 } } > { pages . find ( p => p . hash === pageHash ) ? .component } </ div >
4444 </ div >
4545 ) ;
4646}
0 commit comments