react#ComponentType TypeScript Examples

The following examples show how to use react#ComponentType. 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: icons.stories.tsx    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
Icons = () => {
  return (
    <Grid size={60}>
      {Object.keys(icons).map((iconName) => {
        //@ts-ignore
        const Icon: ComponentType = icons[iconName];
        return (
          <Tooltip title={iconName} placement="right">
            <Icon />
          </Tooltip>
        );
      })}
    </Grid>
  );
}
Example #2
Source File: BaseContainer.tsx    From generator-earth with MIT License 6 votes vote down vote up
contextHoc: (Comp: ComponentType) => ComponentType = function contextHoc(Comp) {
    // class组件
    if ( Comp.prototype.render ) {
        let C = Comp as ComponentClass;
        C.contextType = BaseContext;
        return C;
    // function组件
    } else {
        let fc = Comp as FC
        return function(props) {
            return (
                <BaseContext.Consumer>
                { (context) => fc(props, context) }
                </BaseContext.Consumer>
            )
        }
    }
}
Example #3
Source File: withSharedProps.tsx    From spinners-react with MIT License 6 votes vote down vote up
withSharedProps = <P extends SpinnersProps>(Component: ComponentType<P>) => {
  const Wrapper = (props: P) => {
    const {
      color, enabled, size, style, ...otherProps
    } = props;
    const componentProps = {
      ...otherProps,
      style: {
        color,
        overflow: 'visible',
        width: normalizeSize(size),
        ...style,
      },
    };

    if (!enabled) return null;

    return <Component {...componentProps as P} />;
  };

  Wrapper.defaultProps = defaultProps;

  return Wrapper;
}
Example #4
Source File: ComponentMapping.tsx    From aem-react-editable-components with Apache License 2.0 6 votes vote down vote up
function withComponentMappingContext<P extends MappedComponentProperties>(Component: React.ComponentType<P>): MappingContextFunction<P> {
    return function ComponentMappingContextComponent(props: P): JSX.Element {
        return (
          <ComponentMappingContext.Consumer>
            { (componentMapping: ComponentMapping) => <Component {...props} componentMapping={componentMapping} /> }
          </ComponentMappingContext.Consumer>
        );
    };
}
Example #5
Source File: server.tsx    From react-loosely-lazy with Apache License 2.0 6 votes vote down vote up
export function createComponentServer<C extends ComponentType<any>>({
  dataLazyId,
  defer,
  loader,
  moduleId,
  ssr,
}: {
  dataLazyId: string;
  defer: number;
  loader: ServerLoader<C>;
  moduleId: string;
  ssr: boolean;
}) {
  return (props: ComponentProps<C>) => {
    const Resolved = ssr ? load(moduleId, loader) : null;
    const { fallback } = useContext(LazySuspenseContext);
    const { crossOrigin, manifest } = getConfig();

    return (
      <>
        <input type="hidden" data-lazy-begin={dataLazyId} />
        {defer !== PHASE.LAZY &&
          getAssetUrlsFromId(manifest, moduleId)?.map(url => (
            <link
              key={url}
              rel={defer === PHASE.PAINT ? 'preload' : 'prefetch'}
              href={url}
              crossOrigin={crossOrigin}
              as="script"
            />
          ))}
        {Resolved ? <Resolved {...props} /> : fallback}
        <input type="hidden" data-lazy-end={dataLazyId} />
      </>
    );
  };
}
Example #6
Source File: index.tsx    From react-resource-router with Apache License 2.0 6 votes vote down vote up
getWrappedComponentDisplayName = (
  component: ComponentType<any>
): string => {
  let componentDisplayName = 'UNDEFINED';
  const { displayName, name } = component;

  if (displayName) {
    componentDisplayName = displayName;
  }

  if (name) {
    componentDisplayName = name;
  }

  return `withRouter(${componentDisplayName})`;
}
Example #7
Source File: with-auth0.tsx    From auth0-react with MIT License 6 votes vote down vote up
withAuth0 = <P extends WithAuth0Props>(
  Component: ComponentType<P>
): ComponentType<Omit<P, keyof WithAuth0Props>> => {
  return function WithAuth(props): JSX.Element {
    return (
      <Auth0Context.Consumer>
        {(auth: Auth0ContextInterface): JSX.Element => (
          <Component {...(props as P)} auth0={auth} />
        )}
      </Auth0Context.Consumer>
    );
  };
}
Example #8
Source File: Items.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
SidebarDivider = styled('hr')(
  {
    height: 1,
    width: '100%',
    background: '#383838',
    border: 'none',
    margin: '12px 0px',
  },
  { name: 'BackstageSidebarDivider' },
) as ComponentType<ComponentProps<'hr'> & StyledComponentProps<'root'>>
Example #9
Source File: List.factory.tsx    From ke with MIT License 6 votes vote down vote up
export function makeList(Container: ComponentType, Item: ComponentType): LayoutComponent<Item[]> {
  return ({ children }): JSX.Element => (
    <Container>
      {children.map(([key, node]) => (
        <Item key={key}>{node}</Item>
      ))}
    </Container>
  )
}
Example #10
Source File: index.tsx    From baidu-pan-downloader with MIT License 6 votes vote down vote up
function render(RootComponent: ComponentType) {
  ReactDOM.render(
    <Provider store={store}>
      <Suspense fallback={<div>on suspensing....</div>}>
        <RootComponent />
        <div></div>
      </Suspense>
    </Provider>,
    document.getElementById(name)
  )
}
Example #11
Source File: ComponentLoader.tsx    From foundation-lib-spa-core with Apache License 2.0 6 votes vote down vote up
/**
     * Load a component type synchronously from the cache
     * 
     * @param   component       The name/path of the component
     * @param   throwOnUnknown  Wether or not an error must be thrown if the component is not in the cache
     */
    public getPreLoadedType<P = ComponentProps<IContent>>(component: string, throwOnUnknown = true) : ComponentType<P> | null
    {
        if (this.isPreLoaded(component)) {
            const c = this.cache[component];
            if (!c.displayName) c.displayName = component;
            return c as ComponentType<P>;
        }
        if (throwOnUnknown) {
            throw new Error(`The component ${component} has not been pre-loaded!`);
        }
        return null;
    }
Example #12
Source File: regist-router.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
asyncComponent = (getComponent: () => Promise<ComponentType>) => {
  return class AsyncComponent extends React.Component {
    state = { Component: null as unknown as any };

    componentDidMount() {
      if (!this.state.Component) {
        getComponent().then((Component) => {
          this.setState({ Component });
        });
      }
    }

    render() {
      const { Component } = this.state;
      if (!Component) {
        return null;
      }
      return <Component {...this.props} />;
    }
  };
}
Example #13
Source File: HOCs.tsx    From frontegg-react with MIT License 6 votes vote down vote up
withProtectedRoute = <P extends {}>(Component: ComponentType<P>) =>
  function withProtectedRoute(props: P) {
    const { isAuthenticated, isLoading, loginUrl } = useAuth((state) => ({
      isAuthenticated: state,
      isLoading: state.isLoading,
      loginUrl: state.routes.loginUrl,
    }));
    return isLoading ? null : isAuthenticated ? <Component {...props} /> : onRedirecting(loginUrl);
  }
Example #14
Source File: withFrontegg.tsx    From opensaas with MIT License 6 votes vote down vote up
withFrontegg = <P extends {}>(AppComponent: ComponentType<P>) => (props: P) => {
  return (
    <FronteggProvider plugins={plugins} context={contextOptions}>
      <LegacyProvider contextOptions={legacyContextOptions}>
        <AppComponent {...props} />
      </LegacyProvider>
    </FronteggProvider>
  );
}
Example #15
Source File: grabbable.tsx    From ble with Apache License 2.0 6 votes vote down vote up
grabbable = function<P>(
	Component: ComponentType<P>
): FunctionComponent<P> {
	const WrappedComponent: FunctionComponent<P> = ({ ...props }) => {
		return (
			<Component
				{...props}
				interactive
				cursor="move"
			/>
		);
	};
	WrappedComponent.displayName = `grabbable(${Component.displayName || Component.name || 'Component'})`;

	return WrappedComponent;
}
Example #16
Source File: InjectRandomIds.ts    From gio-design with Apache License 2.0 6 votes vote down vote up
/**
 * 解决 SVG 组件 ID 重复问题的高阶组件
 * @param Component 需要传入的 SVG 组件
 * @returns 注入随机 ID 后的 SVG 组件
 */
export default function InjectRandomIds<P>(
  Component: ComponentType<P>
): ComponentType<P & RefAttributes<SVGSVGElement>> {
  return function WrapperComponent(props) {
    const componentRef = useRef<SVGSVGElement>();
    useLayoutEffect(() => {
      if (!componentRef.current) return;
      const elementsWithId = componentRef.current.querySelectorAll('svg [id]');
      const elementsWithFill = componentRef.current.querySelectorAll('svg [fill^=url\\(\\#]');
      elementsWithId.forEach((element) => {
        const id = element.getAttribute('id');
        const elementsWithFillSameId = filter(elementsWithFill, (item) => item.getAttribute('fill') === `url(#${id})`);
        elementsWithFillSameId.forEach((node) => {
          if (node) {
            const newId = `${id}__${uniqueId()}`;
            element.setAttribute('id', newId);
            node.setAttribute('fill', `url(#${newId})`);
          }
        });
      });
    }, []);
    return React.createElement(Component, { ...props, ref: componentRef });
  };
}
Example #17
Source File: App.tsx    From jitsu with MIT License 6 votes vote down vote up
/**
 * Component decorator that enables analytics services and sets a correct document title
 */
function pageOf(component: React.ComponentType<any>, opts: { pageTitle: string }) {
  return page => {
    ApplicationServices.get().analyticsService.onPageLoad({
      pagePath: page.location.key || "/unknown",
    })
    document["title"] = opts.pageTitle
    const Component = component as ExoticComponent
    return <Component {...(page as any)} />
  }
}
Example #18
Source File: hitComps.tsx    From usehooks-ts with MIT License 6 votes vote down vote up
HitElement: ComponentType<{ hit: Hit<BasicDoc> }> = ({ hit }) => (
  <ListItem
    button
    component={GatsbyLink}
    to={hit.path}
    className={classes.hit}
    key={hit.objectID}
  >
    <Typography className={classes.title} variant="h6" component="span">
      <Highlight attribute="title" hit={hit} />
      ()
    </Typography>
    <Typography variant="body2" color="textSecondary" component="span">
      <Highlight attribute="excerpt" hit={hit} />
    </Typography>
    <Divider />
  </ListItem>
)
Example #19
Source File: Selects.tsx    From core with GNU Affero General Public License v3.0 6 votes vote down vote up
Select: React.FC<SelectProps> = ({ placeholder, options, values, setValues, handleChange, handleTouch }) => {
	const onSortEnd = ({ oldIndex, newIndex }) => {
		const newValue = arrayMove(values, oldIndex, newIndex)
		setValues(newValue)
	}
	return <SortableSelect useDragHandle axis='xy' distance={4} getHelperDimensions={({ node }) => node.getBoundingClientRect()} onSortEnd={onSortEnd}
	// select props
		styles={{
			control: (provided) => {
				return { ...provided, border: 'none' }
			},
			option: (provided) => {
				return { ...provided, cursor: 'pointer', ':hover': {
					opacity: '0.7'
				} }
			}
		}} isMulti className='border border-grey-light dark:border-transparent rounded' classNamePrefix='outline-none text-black dark:bg-very-black dark:text-white cursor-pointer ' placeholder={placeholder || '선택해주세요.'} options={options} onChange={handleChange} onBlur={handleTouch} noOptionsMessage={() => '검색 결과가 없습니다.'}
		value={values.map(el => ({ label: el, value: el}))}
		components={{
			MultiValue: SortableMultiValue as ComponentType<MultiValueProps<OptionTypeBase, GroupTypeBase<{ label: string, value: string}>>>,
			MultiValueLabel: SortableMultiValueLabel,
		}}
		closeMenuOnSelect={false}
	/>
}
Example #20
Source File: ViewerContainer.tsx    From kfp-tekton-backend with Apache License 2.0 6 votes vote down vote up
componentMap: Record<PlotType, ComponentType<any>> = {
  [PlotType.CONFUSION_MATRIX]: ConfusionMatrix,
  [PlotType.MARKDOWN]: MarkdownViewer,
  [PlotType.ROC]: ROCCurve,
  [PlotType.TABLE]: PagedTable,
  [PlotType.TENSORBOARD]: TensorboardViewer,
  [PlotType.VISUALIZATION_CREATOR]: VisualizationCreator,
  [PlotType.WEB_APP]: HTMLViewer,
}
Example #21
Source File: testingUtils.tsx    From crosshare with GNU Affero General Public License v3.0 6 votes vote down vote up
WithAllProviders: (
  opts: AuthOptions,
  includeSnackbar?: boolean
) => ComponentType =
  (opts: AuthOptions, includeSnackbar?: boolean) =>
  ({ children }) => {
    return (
      <I18nProvider i18n={i18n} forceRenderOnLocaleChange={false}>
        <AuthContext.Provider
          value={{
            user: undefined,
            isAdmin: false,
            isPatron: false,
            loading: false,
            error: undefined,
            ...opts,
          }}
        >
          {includeSnackbar ? (
            <SnackbarProvider>{children}</SnackbarProvider>
          ) : (
            children
          )}
        </AuthContext.Provider>
      </I18nProvider>
    );
  }
Example #22
Source File: withSuspense.tsx    From console with GNU Affero General Public License v3.0 6 votes vote down vote up
function withSuspense<P extends string | number | object>(
  WrappedComponent: ComponentType<P>,
  fallback: SuspenseProps["fallback"] = null
) {
  function ComponentWithSuspense(props: P) {
    return (
      <Suspense fallback={fallback}>
        <WrappedComponent {...(props as any)} />
      </Suspense>
    );
  }

  return ComponentWithSuspense;
}
Example #23
Source File: ErrorBoundary.tsx    From mitojs with MIT License 6 votes vote down vote up
WithErrorBoundary = (errorBoundaryProps: ErrorBoundaryProps = {}) =>
  function <C extends ComponentType>(ToWrapComponent: C) {
    // ToWrapComponent may be class component or Function
    const componentDisplayName = ToWrapComponent.displayName || ToWrapComponent.name || 'unknown'
    const wrapped: FC = (props: any) => (
      <ErrorBoundary {...errorBoundaryProps}>
        <ToWrapComponent {...props} />
      </ErrorBoundary>
    )
    wrapped.displayName = `MitoErrorBoundary(${componentDisplayName})`
    return wrapped as C
  }
Example #24
Source File: authorizedOnlyHOC.tsx    From react-js-tutorial with MIT License 6 votes vote down vote up
export function authorizedOnlyHoc<P>(
  Component: ComponentType<P>,
  redirectPath = "/login"
) {
  return (props: P) => {
    const [isAuthorized, setIsAuthorized] = useState(CheckState.initiated);

    useEffect(() => {
      //https://medium.com/javascript-in-plain-english/how-to-use-async-function-in-react-hook-useeffect-typescript-js-6204a788a435
      (async () => {
        const isAuthorized = await isLoggedIn();
        setIsAuthorized(isAuthorized ? CheckState.succeed : CheckState.failed);
      })();
    }, []);

    if (isAuthorized === CheckState.initiated) {
      return <div>Checking if user is authorized</div>;
    }

    if (isAuthorized === CheckState.failed) {
      return <Redirect to={redirectPath} />;
    }

    return <Component {...props} />;
  };
}
Example #25
Source File: TextFilter.tsx    From po8klasie with GNU General Public License v3.0 6 votes vote down vote up
TextFilter: FC<TextFilterProps> = ({ value, onChange, options }) => {
  const handleChange = (e: ChangeEvent<HTMLInputElement>) => onChange(e.target.value);

  const icon = options?.icon as string;
  const Icon = icon
    ? dynamic(
        () => import('react-icons/all').then((bundle) => bundle[icon]) as Promise<ComponentType>,
        {
          ssr: false,
        },
      )
    : () => null;

  return (
    <div className={styles.textInputWrapper}>
      <input
        className={styles.textInput}
        placeholder={options?.placeholder}
        type="text"
        value={value as string}
        onChange={handleChange}
      />
      <Icon />
    </div>
  );
}
Example #26
Source File: DefaultLayoutHOC.tsx    From coindrop with GNU General Public License v3.0 6 votes vote down vote up
withDefaultLayout = (Component: ComponentType): FunctionComponent<Props> => {
    const WrappedComponent: FunctionComponent = (props: Props) => {
        const theme = useTheme();
        return (
            <Container
                maxW={theme.breakpoints.lg}
                mx="auto"
                px={4}
                mb={6}
            >
                <Navbar />
                <Box mb={[2, 0]} />
                <hr />
                <Component {...props} />
                <Footer />
            </Container>
        );
    };
    return WrappedComponent;
}
Example #27
Source File: onlyOn.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
onlyOn =
  (environment: Environment) =>
  <T extends ComponentType<any>>(component: T): T | (() => null) => {
    if (getEnvironment() === environment) {
      return component;
    }

    return () => null;
  }
Example #28
Source File: Root.tsx    From react-pwa with MIT License 6 votes vote down vote up
function render(App: ComponentType) {
  root.render(
    <StrictMode>
      <RecoilRoot>
        <HelmetProvider>
          <ThemeProvider>
            <App />
          </ThemeProvider>
        </HelmetProvider>
      </RecoilRoot>
    </StrictMode>,
  );
}
Example #29
Source File: connectWithCleanUp.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
connectWithCleanUp = <
  TStateProps extends {} = {},
  TDispatchProps = {},
  TOwnProps = {},
  State = {},
  TSelector extends object = {},
  Statics = {}
>(
  mapStateToProps: MapStateToPropsParam<TStateProps, TOwnProps, State>,
  mapDispatchToProps: MapDispatchToPropsParam<TDispatchProps, TOwnProps>,
  stateSelector: StateSelector<TSelector>
) => (Component: ComponentType<any>) => {
  const ConnectedComponent = connect(
    mapStateToProps,
    mapDispatchToProps
    // @ts-ignore
  )(Component);

  const ConnectedComponentWithCleanUp: FunctionComponent = props => {
    const dispatch = useDispatch();
    useEffect(() => {
      return function cleanUp() {
        dispatch(cleanUpAction({ stateSelector }));
      };
    }, []);
    // @ts-ignore
    return <ConnectedComponent {...props} />;
  };

  ConnectedComponentWithCleanUp.displayName = `ConnectWithCleanUp(${ConnectedComponent.displayName})`;
  hoistNonReactStatics(ConnectedComponentWithCleanUp, Component);
  type Hoisted = typeof ConnectedComponentWithCleanUp & Statics;

  return ConnectedComponentWithCleanUp as Hoisted;
}