react#ReactElement TypeScript Examples

The following examples show how to use react#ReactElement. 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: tooltip-element-props.ts    From react-circular-menu with Apache License 2.0 6 votes vote down vote up
getTooltipElementProps = <T>(
  elementProps: ReactElement["props"],
  openTooltip: () => void,
  closeTooltip: () => void
): DOMAttributes<T> => ({
  onMouseEnter: (event) => {
    openTooltip();
    elementProps.onMouseEnter?.(event);
  },
  onMouseLeave: (event) => {
    closeTooltip();
    elementProps.onMouseLeave?.(event);
  },
  onFocus: (event) => {
    openTooltip();
    elementProps.onFocus?.(event);
  },
  onBlur: (event) => {
    closeTooltip();
    elementProps.onBlur?.(event);
  },
  onTouchStart: (event) => {
    openTooltip();
    elementProps.onTouchStart?.(event);
  },
  onTouchEnd: (event) => {
    closeTooltip();
    elementProps.onTouchEnd?.(event);
  },
})
Example #2
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 #3
Source File: index.tsx    From MultiFaucet with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Returns button to add network to MetaMask
 * @param {temp: any} autoconnect details
 * @returns {ReactElement}
 */
function AddNetworkButton({ autoconnect }: { autoconnect: any }): ReactElement {
  /**
   * Adds network to MetaMask
   */
  const addToMetaMask = async () => {
    // @ts-expect-error
    await window.ethereum.request({
      method: "wallet_addEthereumChain",
      params: [autoconnect],
    });
  };

  return (
    <button onClick={addToMetaMask} className={styles.addNetworkButton}>
      Add to MetaMask
    </button>
  );
}
Example #4
Source File: Layout.tsx    From merkle-airdrop-starter with GNU Affero General Public License v3.0 6 votes vote down vote up
// Component styles

export default function Layout({
  children,
}: {
  children: ReactElement | ReactElement[];
}) {
  return (
    // Layout wrapper
    <div className={styles.layout}>
      {/* Site meta */}
      <Meta />

      {/* Global header */}
      <Header />

      {/* Injected child content */}
      <div className={styles.layout__content}>{children}</div>

      {/* Global footer */}
      <Footer />
    </div>
  );
}
Example #5
Source File: Layout.tsx    From pawnft with GNU General Public License v3.0 6 votes vote down vote up
// Jazzicon

/**
 * Layout wrapper for application
 * @param {ReactElement} children to inject into content section
 * @returns {ReactElement} containing layout
 */
export default function Layout({
  children,
}: {
  children: ReactElement;
}): ReactElement {
  return (
    <div>
      {/* Navigation progress bar */}
      <NextNProgress
        color="#127e83"
        startPosition={0.3}
        stopDelayMs={200}
        height={3}
        options={{
          showSpinner: false,
        }}
      />

      {/* Top header component */}
      <Header />

      {/* Content */}
      <div className={styles.layout__content}>{children}</div>

      {/* Bottom footer component */}
      <Footer />
    </div>
  );
}
Example #6
Source File: PriceTextPreview.tsx    From firecms with MIT License 6 votes vote down vote up
export default function PriceTextPreview({
                                                 value, property, size, customProps
                                             }: PreviewComponentProps<number>)
    : ReactElement {

    const classes = useStyles();

    return (
        <div className={value ? undefined : classes.light}>
            {value ? value : "Not available"}
        </div>
    );

}
Example #7
Source File: BaseContainer.tsx    From generator-earth with MIT License 6 votes vote down vote up
contextHoc4FC: 
    ( fc: (props: RouteComponentProps, context: {CONTAINER_ROUTE_PREFIX: string}) => ReactElement )
    => (props: RouteComponentProps) => ReactElement
= function contextHoc(fc) {
    return function(props) {
        return (
            <BaseContext.Consumer>
            { (context) => fc(props, context) }
            </BaseContext.Consumer>
        )
    }
}
Example #8
Source File: ArticleList.tsx    From personal-archive with MIT License 6 votes vote down vote up
useSelectedIDs = (onReload: () => void): [
  number[],
  (id: number, checked: boolean) => void,
  () => ReactElement | null,
] => {
  const [selectedIDs, setSelectedIDs] = useState([] as number[])
  const [fetching, deleteArticles] = useRequestDeleteArticles()

  const select = (id: number, checked: boolean) => {
    if (checked) {
      setSelectedIDs([...selectedIDs, id])
    } else {
      setSelectedIDs(selectedIDs.filter(selectedID => selectedID !== id))
    }
  }

  const onDelete = () =>
    deleteArticles(selectedIDs)
      .then(() => onReload())

  const renderDeleteBtn = (): ReactElement | null =>
    selectedIDs.length > 0 ? (
      <DeleteBtnDiv>
        <Button
          type="criticalSubtle"
          size="small"
          loading={fetching}
          onClick={() => onDelete()}
        >
          Delete
        </Button>
      </DeleteBtnDiv>
    ) : null

  return [selectedIDs, select, renderDeleteBtn]
}
Example #9
Source File: SpotifyIcon.tsx    From spotify-recently-played-readme with MIT License 6 votes vote down vote up
/**
 * SVG of Spotify icon.
 */
export default function SpotifyIcon(): ReactElement {
    return (
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="1em" height="1em" fill="#FFFFFF">
            <path d="M248 8C111.1 8 0 119.1 0 256s111.1 248 248 248 248-111.1 248-248S384.9 8 248 8zm100.7 364.9c-4.2 0-6.8-1.3-10.7-3.6-62.4-37.6-135-39.2-206.7-24.5-3.9 1-9 2.6-11.9 2.6-9.7 0-15.8-7.7-15.8-15.8 0-10.3 6.1-15.2 13.6-16.8 81.9-18.1 165.6-16.5 237 26.2 6.1 3.9 9.7 7.4 9.7 16.5s-7.1 15.4-15.2 15.4zm26.9-65.6c-5.2 0-8.7-2.3-12.3-4.2-62.5-37-155.7-51.9-238.6-29.4-4.8 1.3-7.4 2.6-11.9 2.6-10.7 0-19.4-8.7-19.4-19.4s5.2-17.8 15.5-20.7c27.8-7.8 56.2-13.6 97.8-13.6 64.9 0 127.6 16.1 177 45.5 8.1 4.8 11.3 11 11.3 19.7-.1 10.8-8.5 19.5-19.4 19.5zm31-76.2c-5.2 0-8.4-1.3-12.9-3.9-71.2-42.5-198.5-52.7-280.9-29.7-3.6 1-8.1 2.6-12.9 2.6-13.2 0-23.3-10.3-23.3-23.6 0-13.6 8.4-21.3 17.4-23.9 35.2-10.3 74.6-15.2 117.5-15.2 73 0 149.5 15.2 205.4 47.8 7.8 4.5 12.9 10.7 12.9 22.6 0 13.6-11 23.3-23.2 23.3z" />
        </svg>
    );
}
Example #10
Source File: App.tsx    From GraphAV with MIT License 6 votes vote down vote up
App: React.FC<{}> = (): ReactElement => {
  const [globalTheme, setGlobalTheme] = useState<Theme>(themes.light);
  const [isTutorialVisible, setIsTutorialVisible] = useState<boolean>(
    (localStorage.getItem('isFirstTime') ?? 'true') === 'true'
  );

  const onTutorialExit = () => {
    setIsTutorialVisible(false);
    localStorage.setItem('isFirstTime', 'false');
  };

  const onTutorialOpen = () => {
    setIsTutorialVisible(true);
  };

  return (
    <ThemeProvider theme={globalTheme}>
      <Home onHelpClick={onTutorialOpen} changeTheme={setGlobalTheme}></Home>
      <Tutorial onExit={onTutorialExit} isVisible={isTutorialVisible} />
    </ThemeProvider>
  );
}
Example #11
Source File: Container.tsx    From MLH-Fellow-Map with MIT License 6 votes vote down vote up
function Container({
  children,
  className,
  type,
}: {
  children: ReactElement[];
  className: string;
  type: string;
}) {
  let containerClassName = 'container';

  if (type) {
    containerClassName = `${containerClassName} container-${type}`;
  }

  if (className) {
    containerClassName = `${containerClassName} ${className}`;
  }

  return <div className={containerClassName}>{children}</div>;
}
Example #12
Source File: GlowingButton.tsx    From rari-dApp with GNU Affero General Public License v3.0 6 votes vote down vote up
GlowingButton = ({
  children,
  onClick,
  leftIcon,
  disabled,
  ...boxProps
}: BoxProps & {
  leftIcon?: ReactElement;
  onClick: () => any;
  disabled?: boolean;
}) => {
  return (
    <GlowingBox {...boxProps}>
      <Button
        bg="#FFFFFF"
        color="#000000"
        borderRadius="7px"
        fontWeight="bold"
        width="100%"
        height="100%"
        leftIcon={leftIcon}
        onClick={onClick}
        isDisabled={disabled ?? false}
        _focus={{ boxShadow: "0 0 3pt 3pt #2F74AF" }}
        _disabled={{ cursor: "not-allowed" }}
        fontSize={boxProps.fontSize ?? "xl"}
      >
        {children}
      </Button>
    </GlowingBox>
  );
}
Example #13
Source File: Footer.tsx    From design-system with Apache License 2.0 6 votes vote down vote up
Header: React.FC<FooterProps> = ({ children, ...rest }) => {
	return (
		<SFooter {...rest}>
			<ul className="footer__links">
				{children?.map((link: ReactElement, index: number) => (
					<li className="footer__links-item" key={index}>
						{React.cloneElement(link, { className: 'footer__link' })}
					</li>
				))}
			</ul>
			<span className="footer__copyright">
				© {new Date().getFullYear()} Talend. All rights reserved.
			</span>
		</SFooter>
	);
}
Example #14
Source File: ErrorHandler.tsx    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
render(): ReactElement {
    const { error, errorInfo } = this.state;
    const { children, errorHandler } = this.props;

    // If there is an error, display the error handler
    // instead of the base page.
    if (error) {
      console.error('Error caught, rendering error handler...');
      return createElement(errorHandler, { error, errorInfo });
    }

    // Else, render the child components.
    return <>{children}</>;
  }
Example #15
Source File: icon.tsx    From THUInfo with MIT License 6 votes vote down vote up
HomeIcon = ({
	title,
	onPress,
	children,
}: {
	title: keyof typeof zh;
	onPress: (event: GestureResponderEvent) => void;
	children: ReactElement;
}) => {
	const themeName = useColorScheme();
	const theme = themes(themeName);

	return (
		<TouchableOpacity
			style={{
				marginTop: 12,
				alignItems: "center",
				flexGrow: 0,
				flexShrink: 0,
				flexBasis: "20%",
			}}
			onPress={onPress}>
			{children}
			<Text
				style={{color: theme.colors.text, marginTop: 8}}
				ellipsizeMode="tail"
				numberOfLines={1}>
				{getStr(title)}
			</Text>
		</TouchableOpacity>
	);
}
Example #16
Source File: DcsUnit.tsx    From project-tauntaun with GNU Lesser General Public License v3.0 6 votes vote down vote up
export function DcsUnit(props: DcsUnitProps): ReactElement {
  const { unit, unitOnClick } = props;
  const { dcsStaticData } = DcsStaticDataStateContainer.useContainer();
  const groupCategory = React.useContext(CategoryContext);

  const staticUnit = getStaticUnit(dcsStaticData, groupCategory, unit);

  const onClick = (unit: Unit) => unitOnClick?.(unit);

  const getUnitLabel = (unit: Unit) => {
    const staticCategory = matchCategoryToStaticCategory(groupCategory);

    if (staticCategory === 'vehicles') return staticUnit ? staticUnit.name : unit.type;
    return unit.type;
  };

  return <UnitMarker label={getUnitLabel(unit)} unit={unit} unitMarkerOnClick={onClick} />;
}
Example #17
Source File: index.tsx    From react-app-architecture with Apache License 2.0 6 votes vote down vote up
export default function Component({ exampleProp }: { exampleProp: any }): ReactElement {
  const classes = useStyles();
  const appState = useStateSelector((state) => state.appState);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(sendExample.action('Example Message'));
  }, [dispatch]);

  return <div className={classes.root}></div>;
}
Example #18
Source File: LanguageProvider.tsx    From posso-uscire with GNU General Public License v3.0 6 votes vote down vote up
export function LanguageProvider({ children }): ReactElement {
  const [language, setLanguage] = useState(defaultLanguage);

  return (
    <LanguageContext.Provider value={[language, setLanguage]}>
      {children}
    </LanguageContext.Provider>
  );
}
Example #19
Source File: plugins.ts    From cloud-charts with MIT License 6 votes vote down vote up
pluginManager = {
  register(name: string, p: ReactElement) {
    if (plugins[name]) {
      warn('plugin', `${name} has already registered.`);
      return;
    }
    plugins[name] = p;
  },
  get(name: string) {
    if (!name) {
      return plugins;
    }
    if (!plugins[name]) {
      warn('plugin', `${name} not find!`);
    }
    return plugins[name];
  },
}
Example #20
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 #21
Source File: createCustomBlock.ts    From easy-email with MIT License 6 votes vote down vote up
export function createCustomBlock<T extends IBlockData>(
  block: CreateBlockOption<T> & {
    render: (
      data: T,
      idx: string | null,
      mode: 'testing' | 'production',
      context?: IPage,
      dataSource?: { [key: string]: any }
    ) => IBlockData | ReactElement | null;
  }
): IBlock<T> {
  return {
    ...block,
  };
}
Example #22
Source File: index.ts    From react-panorama with MIT License 6 votes vote down vote up
/**
 * Render a React element into the layout in the supplied container.
 *
 * See [ReactDOM.render](https://reactjs.org/docs/react-dom.html#render) for more information.
 */
export function render(element: ReactElement, container: Panel, callback?: () => void) {
  const panel = container as InternalPanel;

  if (panel._reactPanoramaSymbol !== reactPanoramaSymbol) {
    panel._reactPanoramaSymbol = reactPanoramaSymbol;
    // Container was used in the previous reload cycle
    panel._rootContainer = undefined;
  }

  panel._rootContainer ??= reconciler.createContainer(panel, false, false);

  // @ts-expect-error callback type should be nullable
  reconciler.updateContainer(element, panel._rootContainer, null, callback);
}
Example #23
Source File: App.tsx    From vscode-sound-player with MIT License 6 votes vote down vote up
render(): ReactElement {
        const {
            audioData,
            error,
        } = this.state
        if (audioData) {
            return <SoundPlayer audioData={audioData} />
        } else if (error) {
            return <Error message={error.message} />
        } else {
            return <Loading />
        }
    }
Example #24
Source File: RoutingProvider.test.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
function withRoutingProvider(
  root: ReactElement,
  routeBindings: [ExternalRouteRef, RouteRef][] = [],
) {
  const { routing } = traverseElementTree({
    root,
    discoverers: [childDiscoverer, routeElementDiscoverer],
    collectors: {
      routing: routingV1Collector,
    },
  });

  return (
    <RoutingProvider
      routePaths={routing.paths}
      routeParents={routing.parents}
      routeObjects={routing.objects}
      routeBindings={new Map(routeBindings)}
      basePath=""
    >
      {root}
    </RoutingProvider>
  );
}
Example #25
Source File: FilesList.tsx    From ke with MIT License 6 votes vote down vote up
export function FilesList({
  value,
  onChange,
  listItemIcon = Paperclip,
  linkProps,
}: FilesListProps): ReactElement<FilesListProps> {
  const deleteFile = (file: FileDescriptor): void => {
    const restFiles = value.filter((f) => f.uuid !== file.uuid)
    onChange(restFiles)
  }

  return (
    <List>
      {value.map((file) => (
        <ListItem display="flex" alignItems="center" className={listItemCss} key={file.uuid}>
          <ListIcon as={listItemIcon} />
          {file?.url ? (
            <Link href={file.url} isExternal {...linkProps}>
              {file.name}
            </Link>
          ) : (
            file.name
          )}
          <IconButton
            aria-label="Удалить"
            variant="unstyled"
            size="xs"
            icon={<X color="red" size={16} />}
            ml={2}
            onClick={() => deleteFile(file)}
          />
        </ListItem>
      ))}
    </List>
  )
}
Example #26
Source File: AsyncSelect.tsx    From one-platform with MIT License 5 votes vote down vote up
AsyncSelect = ({
  render,
  onSelect,
  customFilter,
  onTypeaheadInputChanged,
  ...selectProps
}: Props): JSX.Element => {
  const [isOpen, setIsOpen] = useToggle();
  const [options, setOptions] = useState<ReactElement<any, string | JSXElementConstructor<any>>[]>(
    []
  );

  const [typeAhead, setTypeAhead] = useState('');

  useEffect(() => {
    if (!isOpen) {
      setTypeAhead('');
      setOptions([]);
      return;
    }

    setOptions(LOADING);
    render(typeAhead)
      .then((loadedOptions) => {
        setOptions(loadedOptions);
      })
      .catch(() => {
        setOptions([
          <SelectOption
            key="option-error"
            value="Failed to fetch request"
            isPlaceholder
            isDisabled
          />,
        ]);
      });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [typeAhead, isOpen]);

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const onPfeSelect = (...args: any) => {
    // eslint-disable-next-line prefer-spread
    onSelect?.apply(null, args);
    setIsOpen.off();
  };

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const onPfeTypeAheadChange = (value: string) => {
    setTypeAhead(value);
    // eslint-disable-next-line prefer-spread
    if (onTypeaheadInputChanged) onTypeaheadInputChanged(value);
  };

  const onFilter = (a: ChangeEvent<HTMLInputElement> | null, value: string) => {
    if (!value) {
      return options;
    }

    if (!customFilter) return options;

    return options.filter((child) => customFilter(child));
  };

  return (
    <PfeSelect
      {...selectProps}
      onSelect={onPfeSelect}
      isOpen={isOpen}
      onToggle={setIsOpen.toggle}
      onTypeaheadInputChanged={onPfeTypeAheadChange}
      onFilter={customFilter && onFilter}
    >
      {options}
    </PfeSelect>
  );
}
Example #27
Source File: CircleMenu.tsx    From react-circular-menu with Apache License 2.0 5 votes vote down vote up
CircleMenu: FC<Props> = ({
  rotationAngleInclusive = true,
  radius = 2,
  itemSize = 2,
  className,
  menuToggleElement,
  menuToggleClassName,
  onMenuToggle,
  ...props
}) => {
  const [menuActive, setMenuActive] = useState<boolean>(false);
  const childrenCount = Children.count(props.children);
  const itemCount = rotationAngleInclusive ? childrenCount - 1 : childrenCount;
  const toggleMenu = () => {
    const updatedMenuState = !menuActive;
    setMenuActive(updatedMenuState);
    onMenuToggle?.(updatedMenuState);
  };

  const menuToggle = menuToggleElement ? (
    cloneElement(menuToggleElement, {
      onClick: () => {
        menuToggleElement.props.onClick?.();
        toggleMenu();
      },
    })
  ) : (
    <CircleMenuToggle
      className={menuToggleClassName}
      menuActive={menuActive}
      size={itemSize}
      toggleMenu={toggleMenu}
    />
  );

  return (
    <Backdrop className={className} active={menuActive} onClick={toggleMenu}>
      {menuToggle}
      <StyledCircleMenuData>
        {Children.map(props.children, (child, index: number) => {
          // Calculating angle
          let angle = props.startAngle;
          let increment = 0;
          if (childrenCount > 1) {
            increment = Math.round(props.rotationAngle / itemCount);
          }
          angle += index * increment;

          return (
            <CircleMenuItem
              key={"cm-item-" + index}
              {...(child as ReactElement<CircleMenuItemProps>).props}
              size={itemSize}
              menuActive={menuActive}
              radius={radius}
              rotationAngle={angle}
            />
          );
        })}
      </StyledCircleMenuData>
    </Backdrop>
  );
}
Example #28
Source File: RulerTab.tsx    From anchor-web-app with Apache License 2.0 5 votes vote down vote up
RulerTab: <T>(
  props: RulerTabProps<T>,
) => ReactElement<RulerTabProps<T>> = styled(RulerTabBase)`
  position: relative;

  height: ${({ height = defaultHeight }) => height}px;

  ul {
    list-style: none;
    padding: 0;

    display: flex;

    li {
      user-select: none;
      cursor: pointer;

      font-size: 18px;
      font-weight: 500;
      display: grid;
      place-content: center;

      color: ${({ theme }) => theme.dimTextColor};

      &[aria-selected='true'] {
        color: ${({ theme }) => theme.textColor};
      }
    }
  }

  hr.point-ruler {
    pointer-events: none;
    user-select: none;

    transition: transform 0.2s ease-out;

    padding: 0;
    margin: 0;
    border: 0;

    position: absolute;
    bottom: 1px;
    height: ${({ rulerWidth = defaultRulerWidth }) => rulerWidth - 2}px;

    background-color: ${({ theme }) => theme.textColor};
    border-radius: 18px;
  }

  hr.background-ruler {
    pointer-events: none;
    user-select: none;

    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
  }

  &[aria-disabled='true'] {
    pointer-events: none;
    opacity: 0.3;
  }

  @media (max-width: 500px) {
    ul {
      li {
        font-size: 14px;
      }
    }
  }
`
Example #29
Source File: index.tsx    From MultiFaucet with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Returns token address component
 * @param {string} etherscanPrefix of address
 * @param {string?} name if displaying MM connect
 * @param {string} address to display
 * @param {string} ERC20 if asset is an ERC20
 * @returns {ReactElement}
 */
function TokenAddress({
  etherscanPrefix,
  name,
  address,
  ERC20,
}: {
  etherscanPrefix: string;
  name?: string;
  address: string;
  ERC20: boolean;
}): ReactElement {
  /**
   * Adds token to MetaMask
   */
  const addToMetaMask = async () => {
    // @ts-expect-error
    await window.ethereum.request({
      method: "wallet_watchAsset",
      params: {
        type: "ERC20",
        options: {
          address: address,
          symbol: name,
          decimals: 18,
        },
      },
    });
  };

  return (
    <span className={styles.address}>
      <a
        href={`https://${etherscanPrefix}/address/${address}`}
        target="_blank"
        rel="noopener noreferrer"
      >
        {ethers.utils.getAddress(address)}
      </a>
      {ERC20 ? <button onClick={addToMetaMask}>Add to MetaMask</button> : null}
    </span>
  );
}