Skip to content

Instantly share code, notes, and snippets.

@seia-soto
Created July 17, 2023 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seia-soto/d1e5704b7286d0f89245a9592b163a5a to your computer and use it in GitHub Desktop.
Save seia-soto/d1e5704b7286d0f89245a9592b163a5a to your computer and use it in GitHub Desktop.
Check tagName after render
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