react#ReactNode TypeScript Examples

The following examples show how to use react#ReactNode. 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: test-utils.tsx    From react-loosely-lazy with Apache License 2.0 7 votes vote down vote up
App = ({
  children,
  phase,
}: {
  children: ReactNode;
  phase: number;
}) => {
  const { startNextPhase } = useLazyPhase();

  if (phase === PHASE.AFTER_PAINT) {
    startNextPhase();
  }

  return <>{children}</>;
}
Example #2
Source File: utils.ts    From test with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
combinePureChildren = (children: ReactNode): ReactNode[] => {
  let isPrevChildPure: boolean = false
  const childList: ReactNode[] = []

  Children.forEach(children, child => {
    const isCurrentChildPure = typeof child === 'string' || typeof child === 'number'

    if (isPrevChildPure && isCurrentChildPure) {
      const lastIndex = childList.length - 1
      const lastChild = childList[lastIndex]
      childList[lastIndex] = [lastChild, child].join(' ')
    } else {
      childList.push(child)
    }

    isPrevChildPure = isCurrentChildPure
  })

  return childList
}
Example #3
Source File: token-icons.stories.tsx    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
Grid = styled(
  ({ children, className }: { children: ReactNode[]; className?: string }) => (
    <section className={className}>{children}</section>
  ),
)<{ size: number }>`
  display: grid;
  grid-template-columns: repeat(${variants.length}, ${({ size }) => size}px);
  grid-template-rows: repeat(${tokens.length}, ${({ size }) => size}px);

  div {
    display: grid;
    place-content: center;

    img {
      font-size: ${({ size }) => size - 10}px;
      width: 1em;
      height: 1em;
    }
  }
`
Example #4
Source File: LabelValueTable.tsx    From abacus with GNU General Public License v2.0 6 votes vote down vote up
/**
 * A table of label/value pairs.
 */
function LabelValueTable({
  className,
  data,
}: {
  className?: string
  data: { label: string; value: ReactNode }[]
}): JSX.Element {
  return (
    <Table className={className}>
      <TableBody>
        {data.map(({ label, value }) => (
          <TableRow key={label}>
            <TableCell component='th' scope='row' variant='head'>
              {label}
            </TableCell>
            <TableCell>{value}</TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  )
}
Example #5
Source File: FirebaseLoginView.tsx    From firecms with MIT License 6 votes vote down vote up
function LoginButton({
                         icon,
                         onClick,
                         text
                     }: { icon: React.ReactNode, onClick: () => void, text: string }) {
    return (
        <Box m={0.5} width={"100%"}>
            <Button fullWidth
                    variant="outlined"
                    onClick={onClick}>
                <Box sx={{
                    p: "1",
                    display: "flex",
                    width: "240px",
                    height: "32px",
                    alignItems: "center",
                    justifyItems: "center"
                }}>
                    <Box sx={{
                        display: "flex",
                        flexDirection: "column",
                        width: "32px",
                        alignItems: "center",
                        justifyItems: "center"
                    }}>
                        {icon}
                    </Box>
                    <Box sx={{
                        flexGrow: 1,
                        pl: 2,
                        textAlign: "center"
                    }}>{text}</Box>
                </Box>
            </Button>
        </Box>
    )
}
Example #6
Source File: Theme.tsx    From GTAV-NativeDB with MIT License 6 votes vote down vote up
function Theme({ children }: { children: ReactNode }) {
  const settings = useSettings()
  const systemIsDark = useMediaQuery('(prefers-color-scheme: dark)')
  const dark = settings.theme === 'dark' || (settings.theme === 'system' && systemIsDark)
  const theme = useMemo(
    () => createTheme(dark ? darkTheme : lightTheme),
    [dark]
  )

  useEffect(() => {
    document.querySelector('meta[name="theme-color"]')
      ?.setAttribute('content', dark ? '#272727' :'#0e752e')
  }, [dark])

  return (
    <ThemeProvider theme={theme}>
      {children}
    </ThemeProvider>
  )
}
Example #7
Source File: Loader.tsx    From frames with Mozilla Public License 2.0 6 votes vote down vote up
export function Link({children, href, as}: { href: string, as?: string, children: ReactNode }) {
    return (
        <FLink href={href} as={as}>
            <a className={ss.anchor}>
                {children}
            </a>
        </FLink>
    )
}
Example #8
Source File: index.tsx    From rocketseat-gostack-11-desafios with MIT License 6 votes vote down vote up
Upload: React.FC<UploadProps> = ({ onUpload }: UploadProps) => {
  function renderDragMessage(
    isDragActive: boolean,
    isDragRejest: boolean,
  ): ReactNode {
    if (!isDragActive) {
      return (
        <UploadMessage>Selecione ou arraste o arquivo aqui.</UploadMessage>
      );
    }

    if (isDragRejest) {
      return <UploadMessage type="error">Arquivo não suportado</UploadMessage>;
    }

    return <UploadMessage type="success">Solte o arquivo aqui</UploadMessage>;
  }

  return (
    <>
      <Dropzone accept="text/csv" onDropAccepted={(files) => onUpload(files)}>
        {({ getRootProps, getInputProps, isDragActive, isDragReject }): any => (
          <DropContainer
            {...getRootProps()}
            isDragActive={isDragActive}
            isDragReject={isDragReject}
          >
            <input {...getInputProps()} data-testid="upload" />
            {renderDragMessage(isDragActive, isDragReject)}
          </DropContainer>
        )}
      </Dropzone>
    </>
  );
}
Example #9
Source File: conditional-wrapper.tsx    From keycaplendar with MIT License 6 votes vote down vote up
ConditionalWrapper = ({
  children,
  condition,
  wrapper,
}: {
  children: ReactNode;
  condition: boolean;
  wrapper: (children: ReactNode) => JSX.Element;
}) => (condition ? wrapper(children) : <>{children}</>)
Example #10
Source File: ContextMenu.tsx    From freedeck-configurator with GNU General Public License v3.0 6 votes vote down vote up
ContextMenu: React.FC<{
  children: ReactNode | ReactNodeArray;
  menuId: string;
}> = ({ children, menuId }) => {
  const childrenArray = isReactNodeArray(children) ? children : [children];
  const childrenWithDividers = childrenArray.reduce(
    (acc: ReactNodeArray, child, index) => {
      if (!acc.length) return [child];
      acc.push(<Divider key={index} />);
      acc.push(child);
      return acc;
    },
    []
  );
  return (
    <ContextMenuWrapper id={menuId}>
      <Wrapper>{childrenWithDividers}</Wrapper>
    </ContextMenuWrapper>
  );
}
Example #11
Source File: SubscribeFormWithText.tsx    From frontend.ro with MIT License 6 votes vote down vote up
function SubscribeFormWithText(
  { children, className = '' }: { children: ReactNode, className?: string },
) {
  return (
    <div className={`${styles['subscribe-form--with-text']} ${className} d-flex justify-content-between`}>
      <div>
        {children}
      </div>
      <SubscribeForm />
    </div>
  );
}
Example #12
Source File: DataTableCustomFilter.tsx    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
numberInputField(propertyType: NumericPropertyType): ReactNode {
    switch (propertyType) {
      case 'Integer':
        return this.createFilterInput(<IntegerInput onChange={this.onNumberInputChange}/>, true);
      case 'Double':
        return this.createFilterInput(<DoubleInput onChange={this.onNumberInputChange}/>, true);
      case 'Long':
        return this.createFilterInput(<LongInput onChange={this.onNumberInputChange}/>, true);
      case 'BigDecimal':
        return this.createFilterInput(<BigDecimalInput onChange={this.onNumberInputChange}/>, true);
      default:
        return assertNever('property type', propertyType);
    }
  }
Example #13
Source File: index.tsx    From drip-table with MIT License 6 votes vote down vote up
public render() {
    const uiProps = this.props.schema['ui:props'] || {};

    return (
      <Switch
        {...uiProps}
        checked={this.checked}
        checkedChildren={uiProps.checkedChildren as ReactNode || '是'}
        unCheckedChildren={uiProps.uncheckedChildren as ReactNode || '否'}
        onChange={(checked: boolean) => {
          this.props.onChange?.(this.encodeValue(checked));
        }}
      />
    );
  }
Example #14
Source File: Profitable.tsx    From gonear-name with The Unlicense 6 votes vote down vote up
Profitable = ({ bid, balance, children }: { bid: IBid, balance: number, children: ReactNode }) => {

  const isProfitable: boolean = bid && bid.claimPrice && balance > bid.claimPrice ? true : false

  if (!isProfitable) return null

  return (
    <>
      {children}
    </>
  );
}
Example #15
Source File: Context.tsx    From Notepad with MIT License 6 votes vote down vote up
function Context({ children }: { children: ReactNode }) {
  const [alertBox, setAlertBox] = useState<AlertBox>(null);
  const [drawMode, setDrawMode] = useState<boolean>(false);
  const [drawPadRef, setDrawPadRef] = useState({});

  // This function will also set 'isDrawMode' property in localStorage
  const setDrawModeTo = (isDrawMode: boolean) => {
    setDrawMode(isDrawMode);
    localStorage.setItem("isDrawMode", JSON.stringify(isDrawMode));
  };

  useEffect(() => {
    const isDrawMode: string = localStorage.getItem("isDrawMode") || "false";
    if (isDrawMode === "true") setDrawModeTo(true);
    else if (isDrawMode === "false") setDrawModeTo(false);
    else setDrawModeTo(false);
  }, []);

  return (
    <AlertBoxContext.Provider value={{ alertBox, setAlertBox }}>
      <DrawModeContext.Provider
        value={{ drawMode, setDrawMode: setDrawModeTo }}
      >
        <DrawPadRefContext.Provider value={{ drawPadRef, setDrawPadRef }}>
          {children}
        </DrawPadRefContext.Provider>
      </DrawModeContext.Provider>
    </AlertBoxContext.Provider>
  );
}
Example #16
Source File: markdown.tsx    From protect-scotland with Apache License 2.0 6 votes vote down vote up
childrenAsText = (
  children: React.ReactChildren | React.ReactNode | undefined,
  joiner = ''
): string =>
  children
    ? (React.Children.toArray(children).reduce(
        (str, child) =>
          `${str}${joiner}${
            React.isValidElement(child)
              ? childrenAsText(child.props.children, joiner)
              : `${child}`
          }`,
        ''
      ) as string)
    : ''
Example #17
Source File: ErrorBoundary.tsx    From hypertext with GNU General Public License v3.0 6 votes vote down vote up
export default class ErrorBoundary extends Component<{ fallback: ReactNode; children: ReactNode }> {
  state = { hasError: false, error: null }
  static getDerivedStateFromError(error: Error): { hasError: boolean; error: Error } {
    return {
      hasError: true,
      error,
    }
  }
  render(): ReactNode {
    if (this.state.hasError) {
      return this.props.fallback
    }
    return this.props.children
  }
}
Example #18
Source File: Modal.test.tsx    From crowdsource-dataplatform with MIT License 6 votes vote down vote up
describe('Modal', () => {
  const setup = (
    props: {
      title?: string;
      subTitle?: string;
      footer?: ReactNode;
    } = {
      title: 'title',
      subTitle: 'subTitle',
      footer: <button type="submit">Done</button>,
    }
  ) =>
    render(
      <Modal {...props} show>
        <div>Hello world</div>
      </Modal>
    );

  verifyAxeTest(setup());

  it('should render the component and matches it against stored snapshot', () => {
    setup();

    expect(screen.getByTestId('Modal')).toMatchSnapshot();
  });

  it('should render the component and matches it against stored snapshot with default prop values', () => {
    setup({});

    expect(screen.getByTestId('Modal')).toMatchSnapshot();
  });
});
Example #19
Source File: FusePoolCreatePage.tsx    From rari-dApp with GNU Affero General Public License v3.0 6 votes vote down vote up
OptionRow = ({
  children,
  ...others
}: {
  children: ReactNode;
  [key: string]: any;
}) => {
  return (
    <Row
      mainAxisAlignment="space-between"
      crossAxisAlignment="center"
      width="100%"
      my={4}
      px={4}
      overflowX="auto"
      {...others}
    >
      {children}
    </Row>
  );
}
Example #20
Source File: DynamicSlidesExample.tsx    From react-splide with MIT License 6 votes vote down vote up
/**
   * Render the component.
   *
   * @return React node.
   */
  render(): ReactNode {
    return (
      <div className="wrapper">
        <h2 id="dynamic-slides-example-heading">Dynamic Slide Example</h2>

        <Splide
          options={ {
            rewind : true,
            perPage: 2,
            height : '10rem',
            gap    : '1rem',
          } }
          aria-labelledby="dynamic-slides-example-heading"
        >
          { this.state.slides.map( ( slide, index ) => (
            <SplideSlide key={ index }>
              <img src={ slide.src } alt={ slide.alt }/>
            </SplideSlide>
          ) ) }
        </Splide>

        <div className="controls">
          <button onClick={ this.onClick.bind( this ) }>Add Slide</button>
        </div>
      </div>
    );
  }
Example #21
Source File: ApiClientContextController.test.tsx    From react-starter-boilerplate with MIT License 6 votes vote down vote up
describe('ApiClientContextController', () => {
  const wrapper = ({ children }: { children?: ReactNode }) => <>{children}</>;

  test('renders its children', () => {
    const { getByText } = render(
      <ApiClientContextController>
        <span>TEST</span>
      </ApiClientContextController>,
      { wrapper },
    );

    expect(getByText(/TEST/)).toBeInTheDocument();
  });
});
Example #22
Source File: getName.tsx    From sybil-interface with GNU General Public License v3.0 6 votes vote down vote up
export function nameOrAddress(
  address: string | undefined,
  identities: { [address: string]: Identity } | undefined,
  shortern?: boolean | undefined,
  autonomous?: boolean | undefined,
  ens?: string | null
): string | ReactNode {
  const formattedAddress = isAddress(address)

  if (!address) {
    return ''
  }

  // checksum name, as they are checksummed in identity mapping
  const identity: Identity | undefined = formattedAddress ? identities?.[formattedAddress] : undefined

  if (identity?.twitter) {
    return <LogoText type="twitter">{'@' + identity.twitter.handle}</LogoText>
  }

  if (identity?.other) {
    return <LogoText type="other">{identity.other.name}</LogoText>
  }

  if (autonomous) {
    return 'Autonomous Proposal Contract ⚙️'
  }

  if (shortern) {
    return ens ?? shortenAddress(address)
  }

  return ens ?? address
}
Example #23
Source File: htmlProcessor.tsx    From dnde with GNU General Public License v3.0 6 votes vote down vote up
htmlProcessor = (html: string): ReactNode => {
  if (typeof html !== 'string') {
    logger.error('htmlParser: html is not a string');
    return React.createElement('div', {}, 'errors: please check dev console') as ReactNode;
  }

  let doc = domParser.parseFromString(html, 'text/html');

  if (doc === null) {
    logger.error('htmlParser: doc is null, unable to process html');
    return React.createElement('p', {}, 'errors: please check dev console') as ReactNode;
  }
  return converter(doc as unknown as HTMLElement, 1);
}
Example #24
Source File: format.tsx    From ali-react-table with MIT License 6 votes vote down vote up
lfl: RichNumberFormatter = (value: string | number) => {
  if (value == null || value === '-' || isNaN(value as any) || value === Infinity || value === -Infinity) {
    return render('-')
  }
  value = Number(value)
  if (value > 0) {
    return render(
      <>
        <span style={{ color: '#f4485c' }}>{numeral(value).format('0.00%')}</span>
        <BeautifulUpIcon style={{ marginLeft: 4, color: '#f4485c' }} />
      </>,
    )
  }

  if (value < 0) {
    return render(
      <>
        <span style={{ color: '#00a854' }}>{numeral(value).format('0.00%')}</span>
        <BeautifulDownIcon style={{ marginLeft: 4, color: '#00a854' }} />
      </>,
    )
  }

  // value === 0
  return render(<span style={{ color: '#838383' }}>0</span>)

  function render(children: ReactNode) {
    return (
      <div className="lfl-cell" style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'flex-end' }}>
        {children}
      </div>
    )
  }
}
Example #25
Source File: _app.tsx    From website with Apache License 2.0 6 votes vote down vote up
function NavLink(props: {
	children: ReactNode;
	href: string;
	closeMenu?: () => void;
}) {
	return (
		<li className="shrink-0">
			<Link href={props.href}>
				<a className={navlinkClassname} onClick={props.closeMenu}>
					{props.children}
				</a>
			</Link>
		</li>
	);
}
Example #26
Source File: index.tsx    From ab-testing with MIT License 6 votes vote down vote up
ABTestingController: React.FunctionComponent<{
    config: ABTestingConfig;
    userId: number | string;
    userProfile: { [key: string]: string };
    children: ReactNode;
}> = ({ config, userId, userProfile, children }) => {
    const experiments = React.useMemo(
        () => new Experiments(config, userId, userProfile),
        [config, userId, userProfile]
    );
    return <ABTestingContext.Provider value={experiments}>{children}</ABTestingContext.Provider>;
}
Example #27
Source File: index.tsx    From aqualink-app with MIT License 6 votes vote down vote up
MOBILE_SELECT_MENU_ITEMS = Object.values(OrderKeys)
  .filter((key) => DEFAULT_ITEMS.includes(key))
  .reduce<ReactNode[]>(
    (elements, val) => [
      ...elements,
      ...times(2, (i) => {
        const itemOrder: Order = i % 2 === 0 ? "asc" : "desc";
        return (
          <MenuItem value={`${val}-${itemOrder}`} key={val + i}>
            <Typography color="primary" variant="h4">
              {getOrderKeysFriendlyString(val)}
              {"  "}
              {itemOrder === "asc" ? (
                <ArrowDownward fontSize="small" />
              ) : (
                <ArrowUpward fontSize="small" />
              )}
            </Typography>
          </MenuItem>
        );
      }),
    ],
    []
  )
Example #28
Source File: index.ts    From react-panorama with MIT License 6 votes vote down vote up
/**
 * Creates a [React Portal](https://reactjs.org/docs/portals.html).
 */
export function createPortal(
  children: ReactNode,
  container: Panel,
  key?: null | string,
): ReactPortal {
  const portal = {
    $$typeof: REACT_PORTAL_TYPE,
    key: key == null ? null : String(key),
    children,
    containerInfo: container,
  };

  return portal as any;
}
Example #29
Source File: Observable.tsx    From streamlit-observable with MIT License 6 votes vote down vote up
public render = (): ReactNode => {
    return (
      <div style={{ border: '1px solid gray', borderRadius: '4px' }}>
        <div style={{ padding: '9px 12px' }}>
          <div ref={this.notebookRef}></div>
        </div>
        <div style={{ marginTop: '4px' }}>
          
          <div style={{
            backgroundColor: '#ddd',
            fontWeight: 700,
            padding: ".25rem .5rem",
            borderRadius: '0 0 4px 4px',
            gridTemplateColumns: "auto auto",
            display:"grid"
          }}>
            <div style={{textAlign:"left"}}>{this.props.args.name}</div>
            <div style={{textAlign:"right"}}>
            <a href={`https://observablehq.com/${this.props.args.notebook}`} style={{ color: '#666', }}>{this.props.args.notebook}</a>
            </div>
          </div>
        </div>
      </div >
    )
  }