Last active
November 14, 2021 19:38
-
-
Save audunolsen/046d4f9601302d30e5a3c0d3d4483f73 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 React, { createElement } from "react"; | |
/* | |
Tired of writing ((blabla && blabla) && <>blabla</>) | |
*/ | |
interface Props extends React.HTMLAttributes<HTMLElement> { | |
if: any; | |
as?: React.ElementType; | |
children?: React.ReactNode; | |
} | |
const Conditional: React.FC<Props> = ({ | |
if: shouldRender, | |
as: tagName, | |
children, | |
...props | |
}) => { | |
return shouldRender | |
? createElement(tagName ?? React.Fragment, props, children) | |
: null; | |
}; | |
export default Conditional; |
This file contains hidden or 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
{/* TS doesn't work: data possibly undefined */} | |
<Conditional if={data} as="span" className="test"> | |
<strong>{data?.title}</strong> | |
<p>{data?.description}</p> | |
</Conditional> | |
{/* TS works: data always correct type */} | |
{data && ( | |
<span> | |
<strong>{data.title}</strong> | |
<p>{data.description}</p> | |
</span> | |
)} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment