Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React component children detect if empty / null before render

"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

like image 243
user11243583 Avatar asked Mar 22 '19 15:03

user11243583


People also ask

How do you check if a value is empty in React?

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!

How do I know if my React element has children?

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.

Can useRef pass to child component?

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.


2 Answers

Solution 1:

Get the children type. It will return null if Child component returns null:

const isChildNull = children => {   return Boolean(children.type()=== null); }; 

Solution 2:

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

like image 115
lissettdm Avatar answered Oct 13 '22 21:10

lissettdm


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;    ... } 
like image 38
Amine Hakkou Avatar answered Oct 13 '22 19:10

Amine Hakkou