Make Hashrouter auto switch inline

This commit is contained in:
Saahil dutta 2024-07-26 14:45:33 -04:00
parent 87c4f48258
commit 372f16b010
3 changed files with 13 additions and 30 deletions

View file

@ -1,12 +1,22 @@
// writing my own hashRouter
import { useEffect, useState } from "react"
export function HashRouter({ children }: any) {
const [hash, setHash] = useState(window.location.hash)
if(process.env.NODE_ENV !== "production") console.log(children)
if(!Array.isArray(children)) children = [children]
debugger;
useEffect(() => {
const ev = () => {
setHash(window.location.hash)
}
window.addEventListener('hashchange', ev)
return () => window.removeEventListener('hashchange', ev)
})
// debugger;
const child = children.find((child:any) => {
if(process.env.NODE_ENV !== "production") console.log('script', child.props, window.location.hash, child.props.route == window.location.hash, (window.location.hash.length < 2 && child.props.index))
return child.props.path == window.location.hash || (window.location.hash.length < 2 && child.props.index) || child.props.path == "*"
if(process.env.NODE_ENV !== "production") console.log('script', child.props, window.location.hash, child.props.route == hash, (hash.length < 2 && child.props.index))
return child.props.path == hash || (hash.length < 2 && child.props.index) || child.props.path == "*"
})
// console.log('child', child)
if(child) return child.props.component;