Home > OS >  React: detect if children prop is JSX or a function returning JSX
React: detect if children prop is JSX or a function returning JSX

Time:05-06

I want to make a component that can either have JSX or a function that returns JSX as children. when I log the typeof the children prop for the function or JSX, it's both object. How do I detect if the children prop is a function or JSX?

This is what I have so far

type Props = {
    children: ReactNode | ((close: () => void) => ReactNode);
};

const Comp = ({ children }: Props) => (
    {typeof children === 'function' ? children() : children}
)

CodePudding user response:

You condition is fine and you just need to wrap in div. When JSX is transpiled, it will be type of object

const Comp = ({ children }: any) => {
  console.log('***', typeof children);
  return <div>{typeof children === 'function' ? children() : children}</div>;
};

const Element = () => {
  return <div>
  <Comp>{() => <div>Hello</div>}</Comp>
  <Comp><div>Foo</div></Comp>
  </div>
}

const domContainer = document.querySelector('#app');
ReactDOM.render(<Element/>, domContainer);
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

<div id="app"> </div>

  • Related