Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a component is an instance of React.ReactElement<any> in a child map

I have a component that loops through children and wraps them in a div. I am trying to add an exclusion to that, but running into an issue where I can't check if the child is a ReactElement or not (React.ReactChild can be a string, or a number so it may not have a type).

Trying the method below I receive: "'ReactElement' only refers to a type, but is being used as a value here." as well as "Property 'type' does not exist on type 'ReactChild'."

Any help pointing me in the right direction would be greatly appreciated.

  {React.Children.map(children, (child: React.ReactChild) => {
        /**
         * Exclude these components from being
         * wrapped by the item wrapper.
         */
        if (child instanceof React.ReactElement<any> && child.type === Divider) {
          return child;
        }

        if (child) {
          return <div className="l-spacer__item">{React.cloneElement(child as React.ReactElement<any>)}</div>;
        }

        return null;
      })}
like image 597
Ryan Potter Avatar asked Oct 27 '25 07:10

Ryan Potter


1 Answers

You should use React.isValidElement. For your case above:

        if (React.isValidElement(child) && child.type === Divider) {
          return child;
        }
like image 163
mofojed Avatar answered Oct 28 '25 22:10

mofojed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!