Created
July 17, 2023 07:24
-
-
Save seia-soto/d1e5704b7286d0f89245a9592b163a5a to your computer and use it in GitHub Desktop.
Check tagName after render
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { FC, PropsWithChildren, ReactElement, useEffect, useRef, useState } from "react" | |
const GetTagName: FC<PropsWithChildren<{ el?: ReactElement }>> = ({el, children}) => { | |
const [tagName, setTagName] = useState('') | |
const wrapper = useRef(null); | |
useEffect(() => { | |
const inner = wrapper?.current as HTMLElement | null | |
if (!inner) { | |
return; | |
} | |
const nested = inner.querySelector('*') | |
if (!nested) { | |
setTagName('No child provided!') | |
return | |
} | |
setTagName(nested.tagName) | |
}, [wrapper]) | |
return ( | |
<> | |
<div ref={wrapper} style={{display: 'none'}}> | |
{children ?? el} | |
</div> | |
<p>{tagName}</p> | |
</> | |
) | |
} | |
const ProxiedDiv: FC = () => <div /> | |
const ProxiedArticle: FC = () => <><article /></> | |
const App: FC = () => { | |
return ( | |
<> | |
<GetTagName el={<div />} /> | |
<GetTagName el={<article />} /> | |
<GetTagName> | |
<ProxiedDiv /> | |
</GetTagName> | |
<GetTagName> | |
<ProxiedArticle /> | |
</GetTagName> | |
<GetTagName /> | |
</> | |
) | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment