Skip to content

Instantly share code, notes, and snippets.

@smikhalevski
Created January 21, 2022 21:24
Show Gist options
  • Save smikhalevski/a6a1b675a383981f2a67abcdb902c292 to your computer and use it in GitHub Desktop.
Save smikhalevski/a6a1b675a383981f2a67abcdb902c292 to your computer and use it in GitHub Desktop.
React inline functional component
import {createElement, Fragment, isValidElement, ReactElement, ReactNode, useCallback} from 'react';
export interface FcProps<P> {
render(props: P): ReactNode | null | void;
}
function Fc<P extends FcProps<P>>(props: P): ReactElement | null {
const v = useCallback(props.render, [])(props);
return v === undefined ? null : isValidElement(v) ? v : createElement(Fragment, null, v);
}
import {useEffect, useState} from 'react';
import {Fc} from './Fc';
let a = (
<Fc render={() => {
const [count, setCount] = useState(1);
useEffect(() => {
const timeout = setInterval(() => setCount((count) => count + 1), 1_000);
return () => clearInterval(timeout);
}, []);
return count;
}}/>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment