react#Children TypeScript Examples

The following examples show how to use react#Children. 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 test with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
divideChildren = (
  children: ReactNode,
  Wrapper,
  props = {},
): ReactNode | ReactNode[] => {
  if (Children.count(children) > 1) {
    const combinedChildren = combinePureChildren(children)
    const count = combinedChildren.length

    return Children.map(combinedChildren, (child, index) => {
      if (index < count - 1) {
        return createElement(Wrapper, props, child)
      }

      return child
    })
  }

  return children
}
Example #2
Source File: LocalizedText.tsx    From react-native-typescript-starter with MIT License 6 votes vote down vote up
LocalizedText : FC<TextProps> = props => {
    const { style, children, ...rest } = props;
    const { translate } = useLocalization();

    return (
        <Text style={style} {...rest}>
            {Children.map(children, child => {
                if (typeof child === 'string') {
                    return translate(child);
                }

                return child;
            })}
        </Text>
    );
}
Example #3
Source File: DryRunResultsSplitView.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
export function DryRunResultsSplitView(props: { children: ReactNode }) {
  const classes = useStyles();
  const childArray = Children.toArray(props.children);

  if (childArray.length !== 2) {
    throw new Error('must have exactly 2 children');
  }

  return (
    <div className={classes.root}>
      <div className={classNames(classes.child, classes.firstChild)}>
        {childArray[0]}
      </div>
      <Divider orientation="horizontal" />
      <div className={classes.child}>{childArray[1]}</div>
    </div>
  );
}
Example #4
Source File: Carousel.ts    From fe-foundation with Apache License 2.0 6 votes vote down vote up
public cloneChild(originChild: React.ReactNode[]): void {
        const originChildCount = Children.count(originChild);
        const arr: React.ReactNode[] = new Array(originChildCount + 2);

        if (originChildCount <= 1 || this.effect !== 'slide') {
            this.sliders = originChild;
            return;
        }

        Children.forEach(originChild, (child, index) => {
            if (index === 0) {
                arr[originChildCount + 1] = child;
            }

            if (index === originChildCount - 1) {
                arr[0] = child;
            }

            arr[index + 1] = child;
        });

        this.sliders = arr;
    }
Example #5
Source File: Group.tsx    From react-native-wagmi-charts with MIT License 6 votes vote down vote up
export function LineChartGroup({ children, ...props }: Props) {
  const flatChildren = flattenChildren(children);
  const flatChildrenCount = Children.count(flatChildren);
  return (
    <View {...props}>
      {/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
      {Children.map(flatChildren, (child: any, index) => {
        const isLast = index === flatChildrenCount - 1;
        if (!isLast && child.type === LineChart) {
          return cloneElement(child, {
            absolute: true,
          });
        }
        return child;
      })}
    </View>
  );
}
Example #6
Source File: side-nav.tsx    From website with Apache License 2.0 6 votes vote down vote up
Section = ({ children, title }: SectionProps) => {
  const id = `section--${title.toLowerCase().split(' ').join('-')}`;

  return (
    <VerticalStack gap={2} spacing={6}>
      <Heading id={id} as="div" look="h500">
        {title}
      </Heading>
      {Children.map(children, (child) =>
        cloneElement(child as JSX.Element, { 'aria-labelledby': id })
      )}
    </VerticalStack>
  );
}
Example #7
Source File: mdx-components.tsx    From vanilla-extract with MIT License 6 votes vote down vote up
A = ({
  href,
  size, // Omit
  color, // Omit
  type, // Omit
  ...restProps
}: AllHTMLAttributes<HTMLAnchorElement>) => {
  let isInlineCodeLink = false;

  if (
    restProps.children &&
    Children.count(restProps.children) === 1 &&
    typeof restProps.children === 'object'
  ) {
    const child = Children.only(restProps.children);
    if (child && typeof child === 'object' && 'props' in child) {
      isInlineCodeLink =
        child.props.parentName === 'a' &&
        child.props.originalType === 'inlineCode';
    }
  }

  return href ? (
    <Link
      to={href}
      {...restProps}
      inline
      underline="always"
      highlightOnFocus={!isInlineCodeLink}
      className={
        isInlineCodeLink
          ? sprinkles({ color: { lightMode: 'pink700', darkMode: 'gray200' } })
          : undefined
      }
    />
  ) : (
    <a {...restProps} />
  );
}
Example #8
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 #9
Source File: NavLink.tsx    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
NavLink = ({ children, activeClassName = 'active', ...props }: NavLinkProps) => {
  const { pathname } = useRouter();
  const child = Children.only(children) as React.ReactElement;
  const childClassName = child.props.className || '';

  const isActive = pathname === props.href || pathname === props.as;
  const activePath = pathname === '' ? 'index' : pathname;

  const className = cx(childClassName, activePath, { [activeClassName]: isActive });

  const tabRef = useRef<HTMLDivElement>(null);

  // On mobile, scroll selected tab into view
  useEffect(() => {
    if (isActive && tabRef?.current) {
      tabRef.current.scrollIntoView({
        behavior: 'auto',
        block: 'center',
        inline: 'end',
      });
    }
  }, [isActive, tabRef]);

  useEffect(()=>{
    
  }, [props.saveFullScreen])

  return (
    <div ref={tabRef}>
      <Link {...props}>
        {React.cloneElement(child, {
          className: className || null,
        })}
      </Link>
    </div>
  );
}
Example #10
Source File: DOMView.tsx    From react-ecs with MIT License 6 votes vote down vote up
render() {
        if (Children.count(this.props.children) !== 1) {
            throw new Error('<DOMView /> must have a single child.')
        }

        return <>
            {cloneElement(this.props.children, {
                ref: this.ref,
            })}
        </>
    }
Example #11
Source File: TechDocsReaderPage.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
TechDocsReaderPage = (props: TechDocsReaderPageProps) => {
  const { kind, name, namespace } = useParams();
  const { children, entityRef = { kind, name, namespace } } = props;

  const outlet = useOutlet();

  if (!children) {
    const childrenList = outlet ? Children.toArray(outlet.props.children) : [];

    const page = childrenList.find(child => {
      const { type } = child as Extension;
      return !type?.__backstage_data?.map?.get(TECHDOCS_ADDONS_WRAPPER_KEY);
    });

    return (
      <TechDocsReaderPageProvider entityRef={entityRef}>
        {(page as JSX.Element) || <TechDocsReaderLayout />}
      </TechDocsReaderPageProvider>
    );
  }

  return (
    <TechDocsReaderPageProvider entityRef={entityRef}>
      {({ metadata, entityMetadata, onReady }) => (
        <Page themeId="documentation">
          {children instanceof Function
            ? children({
                entityRef,
                techdocsMetadataValue: metadata.value,
                entityMetadataValue: entityMetadata.value,
                onReady,
              })
            : children}
        </Page>
      )}
    </TechDocsReaderPageProvider>
  );
}
Example #12
Source File: index.ts    From frontegg-react with MIT License 6 votes vote down vote up
buildTabsFromChildren = (rootPath: string, children?: ReactNode): [PageTabProps[], string[]] => {
  const invalidTabs: string[] = [];
  let components: any = children;
  if (!children) {
    return [[], invalidTabs];
  }
  if (ReactIs.isFragment(children)) {
    components = components.props.children;
    return buildTabsFromChildren(rootPath, components);
  }
  const tabs: PageTabProps[] = [];

  Children.forEach(components, (child: any, i) => {
    if (typeof child !== 'object') {
      return null;
    }
    if (!child.type.Title || !child.type.route) {
      invalidTabs.push(`${i}`);
    }
    tabs.push({
      Title: child.type.Title ?? (() => `Tab ${tabs.length + 1}`),
      route: joinPaths(rootPath, child.type.route ?? (i === 0 ? rootPath : `/tab-${tabs.length + 1}`)),
      comp: child,
    });
  });
  return [tabs, invalidTabs];
}
Example #13
Source File: FlexCollapse.tsx    From datart with Apache License 2.0 6 votes vote down vote up
Collapse = memo(
  ({ defaultActiveKeys, activeKeys, children }: FlexCollapseProps) => {
    const panels = useMemo(() => {
      let panels: ReactElement[] = [];
      Children.forEach(children, c => {
        if (c.type === Panel) {
          panels.push(cloneElement(c, { defaultActiveKeys, activeKeys }));
        }
      });
      return panels;
    }, [defaultActiveKeys, activeKeys, children]);

    return <Container>{panels}</Container>;
  },
)
Example #14
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 #15
Source File: Card.tsx    From mantine with MIT License 6 votes vote down vote up
Card: CardComponent = forwardRef(
  (props: CardProps<'div'>, ref: PolymorphicRef<'div'>) => {
    const { component, className, p, radius, children, classNames, styles, ...others } =
      useMantineDefaultProps('Card', defaultProps, props);
    const { classes, cx } = useStyles(null, { name: 'Card', classNames, styles });
    const _children = Children.toArray(children);

    const content = _children.map((child, index) => {
      if (typeof child === 'object' && child && 'type' in child && child.type === CardSection) {
        return cloneElement(child, {
          padding: p,
          first: index === 0,
          last: index === _children.length - 1,
        });
      }

      return child;
    });

    return (
      <Paper
        className={cx(classes.root, className)}
        radius={radius}
        p={p}
        component={component || 'div'}
        ref={ref}
        {...others}
      >
        {content}
      </Paper>
    );
  }
) as any
Example #16
Source File: TabMenu.tsx    From pancake-toolkit with GNU General Public License v3.0 6 votes vote down vote up
ButtonMenu: React.FC<TabMenuProps> = ({ activeIndex = 0, onItemClick, children }) => {
  return (
    <Wrapper p={["0 4px", "0 16px"]}>
      <Inner>
        {Children.map(children, (child: ReactElement, index) => {
          const isActive = activeIndex === index;
          return cloneElement(child, {
            isActive,
            onClick: onItemClick ? () => onItemClick(index) : undefined,
            color: isActive ? "backgroundAlt" : "textSubtle",
            backgroundColor: isActive ? "textSubtle" : "input",
          });
        })}
      </Inner>
    </Wrapper>
  );
}
Example #17
Source File: index.tsx    From admin with MIT License 6 votes vote down vote up
Actions: React.FC = ({ children }) => {
  return (
    <div className="border-l border-grey-70 h-full">
      {Children.map(children, (child) => {
        return (
          <div className="flex items-center justify-center border-b border-grey-70 last:border-none h-1/2 w-[72px]">
            {child}
          </div>
        )
      })}
    </div>
  )
}
Example #18
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 #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: icons.stories.tsx    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
Grid = styled(
  ({
    children,
    className,
  }: {
    children: ReactElement[];
    className?: string;
  }) => (
    <section className={className}>
      {Children.toArray(children.map((child) => <div>{child}</div>))}
    </section>
  ),
)<{ size: number }>`
  display: grid;
  grid-template-columns: repeat(5, ${({ size }) => size}px);
  grid-template-rows: repeat(
    ${({ children }) => Math.ceil(children.length / 5)},
    ${({ size }) => size}px
  );

  div {
    display: grid;
    place-content: center;
  }
`
Example #21
Source File: TabMenu.tsx    From vvs-ui with GNU General Public License v3.0 6 votes vote down vote up
ButtonMenu: React.FC<TabMenuProps> = ({ activeIndex = 0, onItemClick, children }) => {
  return (
    <Wrapper p={["0 4px", "0 16px"]}>
      <Inner>
        {Children.map(children, (child: ReactElement, index) => {
          const isActive = activeIndex === index;
          return cloneElement(child, {
            isActive,
            onClick: onItemClick ? () => onItemClick(index) : undefined,
            color: isActive ? "backgroundAlt" : "textSubtle",
            backgroundColor: isActive ? "textSubtle" : "input",
          });
        })}
      </Inner>
    </Wrapper>
  );
}
Example #22
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 #23
Source File: Button.tsx    From panvala with Apache License 2.0 6 votes vote down vote up
Button: React.FunctionComponent<IButton> = props => {
  if (props.large) {
    return (
      <Wrapper>
        <LargeButton {...props}>{Children.toArray(props.children)}</LargeButton>
      </Wrapper>
    );
  }
  return (
    <Wrapper>
      <StyledButton {...props}>{Children.toArray(props.children)}</StyledButton>
    </Wrapper>
  );
}
Example #24
Source File: _document.tsx    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
static async getInitialProps(context: DocumentContext): Promise<DocumentInitialProps> {
    // Render app and page and get the context of the page with collected side effects.
    const sheets = new ServerStyleSheets({
      // injectFirst: true,
      serverGenerateClassName: generateClassName,
    });
    const originalRenderPage = context.renderPage;

    context.renderPage = () =>
      originalRenderPage({
        // The method wraps your React node in a provider element.
        // It collects the style sheets during the rendering so they can be later sent to the client.
        enhanceApp: (App) => (props) => sheets.collect(<App {...props} />),
      });

    console.info(`Performing SSR for path ${context.pathname} (${context.locale})`);

    const initialProps = await Document.getInitialProps(context);

    return {
      ...initialProps,
      // Styles fragment is rendered after the app and page rendering finish.
      styles: [...Children.toArray(initialProps.styles), sheets.getStyleElement()],
    };
  }
Example #25
Source File: ButtonMenu.tsx    From vvs-ui with GNU General Public License v3.0 6 votes vote down vote up
ButtonMenu: React.FC<ButtonMenuProps> = ({
  activeIndex = 0,
  scale = scales.MD,
  variant = variants.PRIMARY,
  onItemClick,
  disabled,
  children,
  fullWidth = false,
  ...props
}) => {
  return (
    <StyledButtonMenu disabled={disabled} variant={variant} fullWidth={fullWidth} {...props}>
      {Children.map(children, (child: ReactElement, index) => {
        return cloneElement(child, {
          isActive: activeIndex === index,
          onClick: onItemClick ? () => onItemClick(index) : undefined,
          scale,
          variant,
          disabled,
        });
      })}
    </StyledButtonMenu>
  );
}
Example #26
Source File: getMenuItems.tsx    From calories-in with MIT License 6 votes vote down vote up
function getMenuItems(children: ReactElement | ReactElement[]) {
  return Children.map(children, (child: ReactElement) => {
    if (child.type === MenuOrDrawerItem) {
      const icon = cloneElement(child.props.icon, { size: 16, mr: 3 })

      return (
        <MenuItem
          disabled={child.props.isDisabled}
          onClick={child.props.onClick}
        >
          {icon}
          {child.props.children}
        </MenuItem>
      )
    } else if (child.type === MenuOrDrawerSeparator) {
      return <MenuDivider />
    }

    return null
  })
}
Example #27
Source File: Group.tsx    From swiftui-react-native with MIT License 6 votes vote down vote up
Group = ({ children, ...rest }: GroupProps) => {
  const groupId = Math.floor(Math.random()) * 1000;
  return (
    <>
      {Children.map(children as ReactElement<any>[], (child, i) =>
        child
          ? cloneElement(child, {
              key: `group-${groupId}-${i}`,
              ...rest,
              ...child.props,
            })
          : null
      )}
    </>
  );
}
Example #28
Source File: CollectionBuilder.ts    From use-platform with MIT License 6 votes vote down vote up
build(props: CollectionProps): Iterable<CollectionNode> {
    const { children } = props

    const builder = this

    return new CacheableList(function* () {
      const items: ReactNode[] = []

      Children.forEach(children, (child) => {
        items.push(child)
      })

      let index = 0
      for (const element of items) {
        const nodes = builder.getNodes({ element }, index)

        for (const node of nodes) {
          yield node
          index++
        }
      }
    })
  }
Example #29
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[];
}