"react": "16.8.4"
Hello, someone knows how to check if there exists children in a (functional) component (before render them)
React.Children.count React.Children.toArray(children)
wont work
the children is $$typeof: Symbol(react.element)
the code example is
function ContextMenuItems(): JSX.Element | null { if (no-items) return null; ... } class ContextMenu extends React.Component { public render(): JSX.Element | null { if (this.props.children === null) { //ContextMenuItems empty check return null; } return <ContextMenu>{this.props.children}</ContextMenu> } }
For any help, idea thankful
To check if a string is empty in React, access its length property and check if it's equal to 0 , e.g. if (str. length === 0) {} . If the string's length is equal to 0 , then the string is empty, otherwise it isn't empty. Copied!
you can check if the component has children by reading the children prop, along with the React. Children. count the code would be: function ContextMenuItems({ children }): JSX.
The forwardRef hooks allows React users to pass refs to child components. The ref can be created and referenced with useRef or createRef and then passed in a parent component.
Get the children type
. It will return null
if Child
component returns null:
const isChildNull = children => { return Boolean(children.type()=== null); };
Using ReactDOMServer.renderToStaticMarkup. It converts the jsx
elements to string
. If children returns null then renderToStaticMarkup
will return an empty string:
import ReactDOMServer from 'react-dom/server'; const isChildNull = children => { return !Boolean(ReactDOMServer.renderToStaticMarkup(children)); };
Usage:
const Child = () => { return null; }; const Parent = ({ children }) => { const isNull = isChildNull(children); if (isNull) { return "render null"; } return <div>{children}</div>; }; export default function App() { return ( <Parent> <Child /> </Parent> ); }
Working example using solution 1
you can check if the component has children by reading the children prop, along with the React.Children.count the code would be:
function ContextMenuItems({ children }): JSX.Element | null { if (!React.Children.count(children)) return null; ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With