react#isValidElement TypeScript Examples

The following examples show how to use react#isValidElement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From yforms with MIT License 7 votes vote down vote up
mergeWithDom = (obj: any, ...params: any[]) => {
  return mergeWith(obj, ...params, (_, srcValue) => {
    // 如果是元素则返回要更改的值,不是则不处理
    if (isValidElement(srcValue)) {
      return srcValue;
    }
    // 如果是不可变数据,不处理合并
    if (isImmutable(srcValue)) {
      return srcValue;
    }
  });
}
Example #2
Source File: utils.ts    From use-platform with MIT License 7 votes vote down vote up
export function isCollectionElement<T = {}>(
  node: ReactNode,
): node is ReactElement<T, CollectionComponent<T>> {
  return (
    isValidElement(node) &&
    typeof node.type === 'function' &&
    typeof (node.type as CollectionComponent).getCollectionNode === 'function'
  )
}
Example #3
Source File: utils.ts    From yforms with MIT License 7 votes vote down vote up
searchSelect = {
  allowClear: true,
  showSearch: true,
  optionFilterProp: 'children',
  filterOption: (input: string, option: any) => {
    const getValue = (dom: React.ReactNode): string => {
      const _value = get(dom, 'props.children');
      if (Array.isArray(_value)) {
        const d = map(_value, (item) => {
          if (isValidElement(item)) {
            return getValue(item);
          }
          return item;
        });
        return join(d, '');
      }
      if (isValidElement(_value)) {
        return getValue(_value);
      }
      return join(_value, '');
    };

    const str = getValue(option);
    return str.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  },
}
Example #4
Source File: Breadcrumbs.tsx    From pancake-toolkit with GNU General Public License v3.0 6 votes vote down vote up
Breadcrumbs: React.FC<BreadcrumbsProps> = ({ separator = DefaultSeparator, children }) => {
  const validItems = Children.toArray(children).filter((child) => isValidElement(child));
  const items = insertSeparators(validItems, separator);

  return (
    <StyledBreadcrumbs>
      {items.map((item, index) => (
        <li key={`child-${index}`}>{item}</li>
      ))}
    </StyledBreadcrumbs>
  );
}
Example #5
Source File: ItemsTypeModify.tsx    From yforms with MIT License 6 votes vote down vote up
CustomModify: YFormFieldBaseProps<any>['modifyProps'] = (props) => {
  const { itemProps = {} } = props;
  const { children } = itemProps;
  return {
    itemProps: {
      viewProps: {
        format: (value, pureValue) => {
          if (pureValue) {
            return value;
          }
          return isValidElement(children) ? (
            <children.type disabled value={value} {...children.props} />
          ) : (
            children
          );
        },
      },
      ...itemProps,
    },
  };
}
Example #6
Source File: flattenChildren.ts    From splitter with MIT License 6 votes vote down vote up
export default function flattenChildren(
  children: ReactNode,
  depth: number = 0,
  keys: (string | number)[] = []
): ReactChild[] {
  return Children.toArray(children).reduce(
    (acc: ReactChild[], node, nodeIndex) => {
      if (isFragment(node)) {
        acc.push.apply(
          acc,
          flattenChildren(
            node.props.children,
            depth + 1,
            keys.concat(node.key || nodeIndex)
          )
        );
      } else {
        if (isValidElement(node)) {
          acc.push(
            cloneElement(node, {
              key: keys.concat(String(node.key)).join('.')
            })
          );
        } else if (typeof node === 'string' || typeof node === 'number') {
          acc.push(node);
        }
      }
      return acc;
    },
    []
  );
}
Example #7
Source File: reactNode.ts    From gio-design with Apache License 2.0 6 votes vote down vote up
export function replaceElement(
  element: React.ReactNode,
  replacement: React.ReactNode,
  props: unknown
): React.ReactNode {
  if (!isValidElement(element)) return replacement;

  return React.cloneElement(element, typeof props === 'function' ? props() : props);
}
Example #8
Source File: label.tsx    From rediagram with MIT License 6 votes vote down vote up
export function useLabelText(
  label?: string | ReactNode,
  { defaultValue, htmlLike = false }: { defaultValue?: string; htmlLike?: boolean } = {},
): string | ReactElement | undefined {
  return useMemo(() => {
    if (isValidElement(label)) {
      return label;
    }
    if (typeof label === 'string') {
      return htmlLike ? transformToHtmlLike(label) : label;
    }
    return htmlLike && defaultValue ? transformToHtmlLike(defaultValue) : defaultValue;
  }, [label, htmlLike, defaultValue]);
}
Example #9
Source File: index.tsx    From livepeer-com with MIT License 6 votes vote down vote up
Breadcrumbs = ({ children }) => {
  const allItems = Children.toArray(children)
    .filter((child) => {
      return isValidElement(child);
    })
    .map((child, index) => (
      <Box
        as="li"
        css={{
          m: 0,
          fontSize: "$3",
          lineHeight: 1.5,
        }}
        key={`child-${index}`}>
        <Box css={{ display: "inline-flex" }}>{child}</Box>
      </Box>
    ));
  return (
    <Box>
      <BreadcrumbsOl>{insertSeparators(allItems)}</BreadcrumbsOl>
    </Box>
  );
}
Example #10
Source File: index.tsx    From web-pdm with Apache License 2.0 6 votes vote down vote up
ButtonActon = CreateComponent<IButtonActon>({
    render: props => {
        const mst = useMst()
        // const disableIcons = mst.Ui.disableIcons.reduce((pre, cur) => ({ ...pre, [cur]: true }), {})

        const { Tooltip } = props
        if (mst.Ui.disableIcons.indexOf(props.icon as any) >= 0) return null
        const IconRender = isValidElement(props.icon)
            ? props.icon
            : props.IconRenders[props.icon as string]
        return (
            <Tooltip title={props.title}>
                <span
                    style={{ color: props.color }}
                    className={classNames({
                        enable: !props.disable,
                        'command-btn': true
                    })}
                    onClick={!props.disable ? props.onClick : undefined}
                >
                    {IconRender}
                </span>
            </Tooltip>
        )
    }
})
Example #11
Source File: index.tsx    From web-pdm with Apache License 2.0 6 votes vote down vote up
handleCircular = () => {
    const cache: any[] = []
    const keyCache: any[] = []
    return (key: any, value: any) => {
        if (typeof value === 'object' && value !== null) {
            if (isValidElement(value)) {
                return reactString(value)
            }
            const index = cache.indexOf(value)

            if (index !== -1) {
                return `[Circular ${keyCache[index]}]`
            }

            cache.push(value)
            keyCache.push(key || 'root')
        }

        return value
    }
}
Example #12
Source File: index.ts    From exevo-pan with The Unlicense 6 votes vote down vote up
getNodeText = (node: React.ReactNode): string => {
  if (!node) return ''

  if (['string', 'number'].includes(typeof node)) return node.toString()

  if (node instanceof Array) return node.map(getNodeText).join('')

  if (isValidElement(node)) return getNodeText(node.props.children)

  return ''
}
Example #13
Source File: Button.tsx    From pancake-toolkit with GNU General Public License v3.0 6 votes vote down vote up
Button = <E extends ElementType = "button">(props: ButtonProps<E>): JSX.Element => {
  const { startIcon, endIcon, external, className, isLoading, disabled, children, ...rest } = props;
  const internalProps = external ? getExternalLinkProps() : {};
  const isDisabled = isLoading || disabled;
  const classNames = className ? [className] : [];

  if (isLoading) {
    classNames.push("pancake-button--loading");
  }

  if (isDisabled && !isLoading) {
    classNames.push("pancake-button--disabled");
  }

  return (
    <StyledButton
      $isLoading={isLoading}
      className={classNames.join(" ")}
      disabled={isDisabled}
      {...internalProps}
      {...rest}
    >
      <>
        {isValidElement(startIcon) &&
          cloneElement(startIcon, {
            mr: "0.5rem",
          })}
        {children}
        {isValidElement(endIcon) &&
          cloneElement(endIcon, {
            ml: "0.5rem",
          })}
      </>
    </StyledButton>
  );
}
Example #14
Source File: index.tsx    From payload with MIT License 6 votes vote down vote up
ButtonContents = ({ children, icon, tooltip }) => {
  const BuiltInIcon = icons[icon];

  return (
    <span className={`${baseClass}__content`}>
      {tooltip && (
        <Tooltip className={`${baseClass}__tooltip`}>
          {tooltip}
        </Tooltip>
      )}
      {children && (
        <span className={`${baseClass}__label`}>
          {children}
        </span>
      )}
      {icon && (
        <span className={`${baseClass}__icon`}>
          {isValidElement(icon) && icon}
          {BuiltInIcon && <BuiltInIcon />}
        </span>
      )}
    </span>
  );
}
Example #15
Source File: repeatedElement.ts    From plasmic with MIT License 6 votes vote down vote up
repeatedElementFn = <T>(isPrimary: boolean, elt: T): T => {
  if (isPrimary) {
    return elt;
  }
  if (Array.isArray(elt)) {
    return (elt.map((v) => repeatedElement(isPrimary, v)) as any) as T;
  }
  if (elt && isValidElement(elt) && typeof elt !== "string") {
    return (cloneElement(elt) as any) as T;
  }
  return elt;
}
Example #16
Source File: index.tsx    From datart with Apache License 2.0 6 votes vote down vote up
export function Popup({
  content,
  overlayClassName,
  onVisibleChange,
  ...rest
}: PopoverProps) {
  const [visible, setVisible] = useState(false);

  const visibleChange = useCallback(
    v => {
      setVisible(v);
      onVisibleChange && onVisibleChange(v);
    },
    [onVisibleChange],
  );

  const onClose = useCallback(() => {
    setVisible(false);
  }, []);

  const injectedContent = useMemo(
    () =>
      isValidElement(content) ? cloneElement(content, { onClose }) : content,
    [content, onClose],
  );

  const className = mergeClassNames(overlayClassName, 'datart-popup');
  return (
    <Popover
      {...rest}
      overlayClassName={className}
      content={injectedContent}
      visible={visible}
      onVisibleChange={visibleChange}
    />
  );
}
Example #17
Source File: index.tsx    From react-amap with MIT License 6 votes vote down vote up
Polygon = forwardRef<PolygonProps, PolygonProps>((props, ref) => {
  const { children } = props;
  const { polygon } = usePolygon(props);
  useImperativeHandle(ref, () => ({ ...props, polygon }));
  if (children && isValidElement(children)) {
    return cloneElement(children, { ...props, polygon });
  }
  return null;
})
Example #18
Source File: parseFields.tsx    From amiya with MIT License 6 votes vote down vote up
/**
 * 转化表单项了里面所有的表达式
 * @param fields 当前配置项
 * @param formatValues 表单的值
 * @returns 新的配置项
 */
export default function parseFields(fields: Array<AyFormField>, formatValues: FormValues) {
  const loop = (field: AyFormField) => {
    let newField = field
    for (let key in newField) {
      let value = newField[key]
      if (Array.isArray(value) && key === 'children') {
        // 携带子元素
        newField[key] = value.map(field => loop({ ...field }))
      } else if (isObj(value)) {
        // 过滤掉 moment 方法、ReactElement 节点
        if (moment.isMoment(value) || isValidElement(value)) {
          continue
        }
        newField[key] = loop({ ...value })
      } else if (isExpression(value)) {
        // 把表达式转化成值
        newField[key] = parseExpression(value, formatValues)
      }
    }
    return newField
  }
  return fields.map(field => {
    return loop({ ...field })
  })
}
Example #19
Source File: index.tsx    From exevo-pan with The Unlicense 6 votes vote down vote up
RadioGroup = ({
  className,
  children,
  indexValue: indexProp,
  onChange,
  ...props
}: RadioGroupProps) => {
  const [innerIndex, setInnerIndex] = useState<number | undefined>(indexProp)
  const derivedActiveIndex = indexProp ?? innerIndex

  return (
    <div
      role="radiogroup"
      aria-activedescendant={indexToId(derivedActiveIndex)}
      className={clsx('grid gap-3', className)}
      {...props}
    >
      {Children.map(children, (child, index) => {
        if (!isValidElement(child)) return child
        if (typeof child.type === 'string') return child

        return cloneElement(child, {
          id: indexToId(index),
          active: derivedActiveIndex === index,
          onClick: () => {
            setInnerIndex((prevInnerIndex) => {
              if (prevInnerIndex !== index) onChange?.(index)
              return index
            })
          },
        })
      })}
    </div>
  )
}
Example #20
Source File: Circles.tsx    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
function CirclesBase({
  className,
  children,
  backgroundColors = ['#ffffff'],
}: CirclesProps) {
  return (
    <div className={className}>
      {Array.isArray(children)
        ? children
            .filter((el) => isValidElement(el))
            .map((element, i) => (
              <figure
                key={'circle' + i}
                style={{
                  backgroundColor:
                    backgroundColors[i % backgroundColors.length],
                }}
              >
                {element}
              </figure>
            ))
        : isValidElement(children) && (
            <figure style={{ backgroundColor: backgroundColors[0] }}>
              {children}
            </figure>
          )}
    </div>
  );
}
Example #21
Source File: Layout.tsx    From backstage-plugin-opsgenie with MIT License 6 votes vote down vote up
function createSubRoutesFromChildren(
  childrenProps: React.ReactNode,
): SubRoute[] {
  // Directly comparing child.type with Route will not work with in
  // combination with react-hot-loader in storybook
  // https://github.com/gaearon/react-hot-loader/issues/304
  const routeType = (
    <Route path="" title="">
      <div />
    </Route>
  ).type;

  return Children.toArray(childrenProps).flatMap(child => {
    if (!isValidElement(child)) {
      return [];
    }

    if (child.type === Fragment) {
      return createSubRoutesFromChildren(child.props.children);
    }

    if (child.type !== routeType) {
      throw new Error('Child of ExploreLayout must be an ExploreLayout.Route');
    }

    const { path, title, children, tabProps } = child.props;
    return [{ path, title, children, tabProps }];
  });
}
Example #22
Source File: useLoading.tsx    From react-loading with MIT License 6 votes vote down vote up
/**
 * Hook returning Indicator element according to loading argument.
 * @example const { containerProps, indicatorEl } = useLoading({ loading: true })
 */
export function useLoading({
  loading = false,
  indicator,
  loaderProps = {},
}: Props) {
  const containerProps = {
    'aria-busy': loading,
    'aria-live': 'polite' as AriaLive,
  };

  const loaderContext = useLoaderContext();
  const indicatorEl = indicator ?? loaderContext?.indicator;
  invariant(
    isValidElement(indicatorEl),
    'Expected a valid React element as indicator'
  );

  const accessibleLoaderProps = (() => {
    const { valueText, ...rest } = loaderProps;
    return {
      role: 'progressbar',
      'aria-valuetext': valueText,
      ...rest,
    };
  })();
  const accessibleIndicator = indicatorEl
    ? cloneElement(indicatorEl, accessibleLoaderProps)
    : null;

  return {
    containerProps,
    indicatorEl: loading ? accessibleIndicator : null,
  };
}
Example #23
Source File: components.tsx    From easy-email with MIT License 6 votes vote down vote up
// Checks whether `element` is a React element of type `Component` (or one of
// the passed components, if `Component` is an array of React components).
export function isElementOfType<P>(
  element: React.ReactNode | null | undefined,
  Component: React.ComponentType<P> | React.ComponentType<P>[],
): boolean {
  if (
    element == null ||
    !isValidElement(element) ||
    typeof element.type === 'string'
  ) {
    return false;
  }

  const { type: defaultType } = element;
  // Type override allows components to bypass default wrapping behavior. Ex: Stack, ResourceList...
  // See https://github.com/Shopify/app-extension-libs/issues/996#issuecomment-710437088
  const overrideType = element.props?.__type__;
  const type = overrideType || defaultType;
  const Components = Array.isArray(Component) ? Component : [Component];

  return Components.some(
    (AComponent) => typeof type !== 'string' && isComponent(AComponent, type),
  );
}
Example #24
Source File: components.tsx    From easy-email with MIT License 6 votes vote down vote up
// Returns all children that are valid elements as an array. Can optionally be
// filtered by passing `predicate`.
export function elementChildren<T extends React.ReactElement>(
  children: React.ReactNode,
  predicate: (element: T) => boolean = () => true,
): T[] {
  return Children.toArray(children).filter(
    (child) => isValidElement(child) && predicate(child as T),
  ) as T[];
}
Example #25
Source File: childrenSerializer.ts    From engine with MIT License 6 votes vote down vote up
childrenSerializer: ValueSerializer = {
  type: GraphNodeType.EXTERNAL,
  name: "children",
  serializer: (value) => {
    if (
      value instanceof Array &&
      value.includes((x: any) => !isValidElement(x))
    ) {
      return;
    } else if (!isValidElement(value)) {
      return;
    }
    const result = JSON.stringify(value, circular());
    return result;
  },
}
Example #26
Source File: TabbedLayout.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
export function createSubRoutesFromChildren(
  childrenProps: ReactNode,
): SubRoute[] {
  // Directly comparing child.type with Route will not work with in
  // combination with react-hot-loader in storybook
  // https://github.com/gaearon/react-hot-loader/issues/304
  const routeType = (
    <Route path="" title="">
      <div />
    </Route>
  ).type;

  return Children.toArray(childrenProps).flatMap(child => {
    if (!isValidElement(child)) {
      return [];
    }

    if (child.type === Fragment) {
      return createSubRoutesFromChildren(child.props.children);
    }

    if (child.type !== routeType) {
      throw new Error('Child of TabbedLayout must be an TabbedLayout.Route');
    }

    const { path, title, children, tabProps } = child.props;
    return [{ path, title, children, tabProps }];
  });
}
Example #27
Source File: useElementFilter.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
function selectChildren(
  rootNode: ReactNode,
  featureFlagsApi: FeatureFlagsApi,
  selector?: (element: ReactElement<unknown>) => boolean,
  strictError?: string,
): Array<ReactElement<unknown>> {
  return Children.toArray(rootNode).flatMap(node => {
    if (!isValidElement(node)) {
      return [];
    }

    if (node.type === Fragment) {
      return selectChildren(
        node.props.children,
        featureFlagsApi,
        selector,
        strictError,
      );
    }

    if (getComponentData(node, 'core.featureFlagged')) {
      const props = node.props as { with: string } | { without: string };
      const isEnabled =
        'with' in props
          ? featureFlagsApi.isActive(props.with)
          : !featureFlagsApi.isActive(props.without);
      if (isEnabled) {
        return selectChildren(
          node.props.children,
          featureFlagsApi,
          selector,
          strictError,
        );
      }
      return [];
    }

    if (selector === undefined || selector(node)) {
      return [node];
    }

    if (strictError) {
      throw new Error(strictError);
    }

    return selectChildren(
      node.props.children,
      featureFlagsApi,
      selector,
      strictError,
    );
  });
}
Example #28
Source File: cellDescToProps.ts    From ke with MIT License 5 votes vote down vote up
function isCellGenerator<T, CProps, Extra>(
  cellDesc: CellDesc<CProps, T, Extra>
): cellDesc is CellConfigGenerator<CProps, T, Extra> | CellNodeGenerator<T, Extra> {
  return typeof cellDesc === 'function' && !isValidElement(cellDesc)
}
Example #29
Source File: SimpleStepper.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
export function SimpleStepper(props: PropsWithChildren<StepperProps>) {
  const { children, elevated, onStepChange, activeStep = 0 } = props;
  const [stepIndex, setStepIndex] = useState<number>(activeStep);
  const [stepHistory, setStepHistory] = useState<number[]>([0]);

  useEffect(() => {
    setStepIndex(activeStep);
  }, [activeStep]);

  const steps: React.ReactNode[] = [];
  let endStep;
  Children.forEach(children, child => {
    if (isValidElement(child)) {
      if (child.props.end) {
        endStep = child;
      } else {
        steps.push(child);
      }
    }
  });

  return (
    <>
      <VerticalStepperContext.Provider
        value={{
          stepIndex,
          setStepIndex,
          stepHistory,
          setStepHistory,
          onStepChange,
          stepperLength: Children.count(children),
        }}
      >
        <MuiStepper
          activeStep={stepIndex}
          orientation="vertical"
          elevation={elevated ? 2 : 0}
        >
          {steps}
        </MuiStepper>
      </VerticalStepperContext.Provider>
      {stepIndex >= Children.count(children) - 1 && endStep}
    </>
  );
}