Skip to content

Instantly share code, notes, and snippets.

@audunolsen
Last active November 14, 2021 19:38
Show Gist options
  • Save audunolsen/046d4f9601302d30e5a3c0d3d4483f73 to your computer and use it in GitHub Desktop.
Save audunolsen/046d4f9601302d30e5a3c0d3d4483f73 to your computer and use it in GitHub Desktop.
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;
{/* 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