react#ComponentProps TypeScript Examples

The following examples show how to use react#ComponentProps. 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: Data.tsx    From plasmic with MIT License 6 votes vote down vote up
export function DynamicElement<
  Tag extends keyof JSX.IntrinsicElements = "div"
>({
  tag = "div",
  className,
  children,
  propSelectors,
  ...props
}: CommonDynamicProps & ComponentProps<Tag>) {
  const computed = _useSelectors(propSelectors);
  return createElement(tag, {
    children,
    ...props,
    ...computed,
    className: className + " " + computed.className,
  });
}
Example #2
Source File: CallDisplay.stories.tsx    From useDApp with MIT License 6 votes vote down vote up
Template: Story<ComponentProps<typeof CallDisplay>> = (args) => (
  <NameTagsContext.Provider
    value={{
      nameTags: [],
      setNameTags: () => undefined,
      getNameTag: (a) => (a === ADDRESS_3 ? 'Uncle Joe' : undefined),
    }}
  >
    <GlobalStyle />
    <CallDisplay {...args} />
  </NameTagsContext.Provider>
)
Example #3
Source File: button.tsx    From vital with MIT License 6 votes vote down vote up
Button = forwardRef<
  HTMLButtonElement,
  Omit<ComponentProps<"button">, "className">
>(({ children, ...rest }, ref) => {
  return (
    <button ref={ref} className={styles.button} {...rest}>
      {children}
    </button>
  );
})
Example #4
Source File: blog.tsx    From portfolio with MIT License 6 votes vote down vote up
getStaticProps: GetStaticProps<{
  posts: ComponentProps<typeof ListLayout>['posts'];
  initialDisplayPosts: ComponentProps<typeof ListLayout>['initialDisplayPosts'];
  pagination: ComponentProps<typeof ListLayout>['pagination'];
}> = async () => {
  const posts = await getAllFilesFrontMatter('blog');
  const initialDisplayPosts = posts.slice(0, POSTS_PER_PAGE);
  const pagination = {
    currentPage: 1,
    totalPages: Math.ceil(posts.length / POSTS_PER_PAGE),
  };

  return { props: { initialDisplayPosts, posts, pagination } };
}
Example #5
Source File: ThemedSkeleton.tsx    From mStable-apps with GNU Lesser General Public License v3.0 6 votes vote down vote up
ThemedSkeleton: FC<ComponentProps<typeof Skeleton> & { className?: string }> = props => {
  const isDarkTheme = useIsDarkMode()
  const theme = colorTheme(isDarkTheme)
  const { className } = props
  return (
    <div className={className}>
      <SkeletonTheme color={theme.background[2]} highlightColor={theme.background[0]}>
        <Skeleton {...props} />
      </SkeletonTheme>
    </div>
  )
}
Example #6
Source File: Filters.tsx    From condo with MIT License 6 votes vote down vote up
getSelectFilterDropdown = (selectProps: ComponentProps<typeof Select>, containerStyles?: CSSProperties) => {
    return ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => {
        return (
            <SelectFilterContainer
                clearFilters={clearFilters}
                showClearButton={selectedKeys && selectedKeys.length > 0}
                style={containerStyles}
            >
                <Select
                    showArrow
                    style={DROPDOWN_SELECT_STYLE}
                    value={selectedKeys}
                    optionFilterProp={'label'}
                    onChange={(e) => {
                        setSelectedKeys(e)
                        confirm({ closeDropdown: false })
                    }}
                    {...selectProps}
                />
            </SelectFilterContainer>
        )
    }
}
Example #7
Source File: Filters.tsx    From condo with MIT License 6 votes vote down vote up
getGQLSelectFilterDropdown = (
    props: ComponentProps<typeof GraphQlSearchInput>,
    search: (client: ApolloClient<Record<string, unknown>>, queryArguments: string) => Promise<Array<Record<string, unknown>>>,
    mode?: ComponentProps<typeof GraphQlSearchInput>['mode'],
    containerStyles?: CSSProperties
) => {
    return ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => {
        return (
            <SelectFilterContainer
                clearFilters={clearFilters}
                showClearButton={selectedKeys && selectedKeys.length > 0}
                style={containerStyles}
            >
                <GraphQlSearchInput
                    style={GRAPHQL_SEARCH_INPUT_STYLE}
                    search={search}
                    showArrow
                    mode={mode}
                    value={selectedKeys}
                    onChange={(e) => {
                        setSelectedKeys(e)
                        confirm({ closeDropdown: false })
                    }}
                    {...props}
                />
            </SelectFilterContainer>
        )
    }
}
Example #8
Source File: Filters.tsx    From condo with MIT License 6 votes vote down vote up
getDateRangeFilterDropdown = (
    props: ComponentProps<typeof DateRangePicker>,
    containerStyles?: CSSProperties
) => {
    return ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => {
        const pickerProps = {
            value: undefined,
            onChange: e => {
                setSelectedKeys([e[0].toISOString(), e[1].toISOString()])
                confirm({ closeDropdown: false })
            },
            allowClear: false,
        }

        if (selectedKeys && selectedKeys.length > 0) {
            pickerProps.value = [dayjs(selectedKeys[0]), dayjs(selectedKeys[1])]
        }

        return (
            <FilterContainer clearFilters={clearFilters}
                showClearButton={selectedKeys && selectedKeys.length > 0}
                style={containerStyles}
            >
                <DateRangePicker {...pickerProps} {...props}/>
            </FilterContainer>
        )
    }
}
Example #9
Source File: MobileUserMenu.tsx    From condo with MIT License 6 votes vote down vote up
modalStyle: ComponentProps<typeof Modal>['style'] = {
    position: 'absolute',
    left: 0,
    right: 0,
    bottom: 0,
    pointerEvents: 'initial',
    top: 'initial',
    transformOrigin: 'initial',
    maxWidth: '100%',
}
Example #10
Source File: editor.tsx    From bext with MIT License 6 votes vote down vote up
Editor: FC<ComponentProps<typeof MonacoEditor>> = (props) => {
  const theme = useBextTheme();

  const onMount = useCallback((_, monaco: Monaco) => {
    monaco.languages.typescript.javascriptDefaults.addExtraLib(
      LIB_UI_DTS,
      '@bext/ui.d.ts',
    );
    monaco.languages.typescript.javascriptDefaults.addExtraLib(
      LIB_UTIL_DTS,
      '@bext/util.d.ts',
    );
    monaco.languages.typescript.javascriptDefaults.addExtraLib(
      LIB_CONTEXT_DTS,
      '@bext/context.d.ts',
    );
  }, []);

  return (
    <MonacoEditor
      {...props}
      theme={theme === 'dark' ? 'vs-dark' : 'vs'}
      onMount={onMount}
    />
  );
}
Example #11
Source File: Twitter.tsx    From plasmic with MIT License 6 votes vote down vote up
export function registerTimelineWrapper(
  loader?: { registerComponent: typeof registerComponent },
  customTimelineWrapper?: ComponentMeta<ComponentProps<typeof TimelineWrapper>>
) {
  if (loader) {
    loader.registerComponent(
      TimelineWrapper,
      customTimelineWrapper ?? timelineWrapper
    );
  } else {
    registerComponent(
      TimelineWrapper,
      customTimelineWrapper ?? timelineWrapper
    );
  }
}
Example #12
Source File: Twitter.tsx    From plasmic with MIT License 6 votes vote down vote up
export function registerTweetWrapper(
  loader?: { registerComponent: typeof registerComponent },
  customTweetWrapper?: ComponentMeta<ComponentProps<typeof TweetWrapper>>
) {
  if (loader) {
    loader.registerComponent(TweetWrapper, customTweetWrapper ?? tweetWrapper);
  } else {
    registerComponent(TweetWrapper, customTweetWrapper ?? tweetWrapper);
  }
}
Example #13
Source File: Twitter.tsx    From plasmic with MIT License 6 votes vote down vote up
export function registerFollowWrapper(
  loader?: { registerComponent: typeof registerComponent },
  customFollowWrapper?: ComponentMeta<ComponentProps<typeof FollowWrapper>>
) {
  if (loader) {
    loader.registerComponent(
      FollowWrapper,
      customFollowWrapper ?? followWrapper
    );
  } else {
    registerComponent(FollowWrapper, customFollowWrapper ?? followWrapper);
  }
}
Example #14
Source File: Twitter.tsx    From plasmic with MIT License 6 votes vote down vote up
tweetWrapper: ComponentMeta<ComponentProps<
  typeof TweetWrapper
>> = {
  name: "hostless-react-twitter-widgets-tweet",
  displayName: "Tweet",
  importName: "TweetWrapper",
  importPath: "@plasmicpkgs/react-twitter-widgets",
  props: {
    tweetId: {
      type: "string",
      description: "The tweet ID",
      defaultValue: "1381980305305694209",
    },
    theme: {
      type: "choice",
      description: "Toggle the default color scheme",
      options: ["dark", "light"],
      defaultValueHint: "light",
    },
  },
  defaultStyles: {
    display: "flex",
    flexDirection: "column",
    overflowY: "auto",
  },
}
Example #15
Source File: Twitter.tsx    From plasmic with MIT License 6 votes vote down vote up
followWrapper: ComponentMeta<ComponentProps<
  typeof FollowWrapper
>> = {
  name: "hostless-react-twitter-widgets-follow",
  displayName: "Follow",
  importName: "FollowWrapper",
  importPath: "@plasmicpkgs/react-twitter-widgets",
  props: {
    username: {
      type: "string",
      description: "Twitter username to follow",
      defaultValue: "plasmicapp",
    },
    large: {
      type: "boolean",
      description: "Toggle the button size",
    },
  },
}
Example #16
Source File: index.tsx    From questdb.io with Apache License 2.0 6 votes vote down vote up
function splitNavItemsByPosition(
  items: Array<ComponentProps<typeof NavbarItem>>,
): {
  leftItems: Array<ComponentProps<typeof NavbarItem>>
  rightItems: Array<ComponentProps<typeof NavbarItem>>
} {
  const leftItems = items.filter(
    (item) =>
      // @ts-expect-error: temporary, will be fixed in Docusaurus TODO remove soon
      (item.position ?? DefaultNavItemPosition) === "left",
  )
  const rightItems = items.filter(
    (item) =>
      // @ts-expect-error: temporary, will be fixed in Docusaurus TODO remove soon
      (item.position ?? DefaultNavItemPosition) === "right",
  )
  return {
    leftItems,
    rightItems,
  }
}
Example #17
Source File: Toast.tsx    From ui with MIT License 6 votes vote down vote up
function Message({
  children,
  ...props
}: ComponentProps<typeof Typography.Text>) {
  return (
    <Typography.Text className={ToastStyles['sbui-toast-message']} {...props}>
      {children}
    </Typography.Text>
  )
}
Example #18
Source File: Toast.tsx    From ui with MIT License 6 votes vote down vote up
function Description({
  children,
  ...props
}: ComponentProps<typeof Typography.Text>) {
  return (
    <Typography.Text
      className={ToastStyles['sbui-toast-description']}
      {...props}
    >
      {children}
    </Typography.Text>
  )
}
Example #19
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 #20
Source File: DendronTOC.tsx    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
DendronTOC = ({
  note,
  ...rest
}: {
  note: NoteProps;
} & ComponentProps<typeof Anchor>) => {
  return (
    <>
      <Anchor style={{ zIndex: 1 }} className="dendron-toc" {...rest}>
        {Object.entries(note?.anchors).map(([key, entry]) =>
          entry?.type === "header" ? (
            <Link
              key={key}
              href={`#${key}`}
              // `anchor.text` contains clean, user displayable text for
              // headings. It should always exist for exported notes, but we
              // have this fallback just in case.
              title={entry?.text ?? unslug(entry?.value)}
            />
          ) : (
            <></>
          )
        )}
      </Anchor>
    </>
  );
}
Example #21
Source File: hero.tsx    From compose-starter-helpcenter-nextjs with MIT License 6 votes vote down vote up
Hero = ({ fields }: TypeComponent_hero) => {
  const { title, text, ctaText, ctaLink, image } = fields;
  const textComp = isRichText(text) ? renderRichText(text) : text;
  const linkProps: Omit<ComponentProps<typeof Link>, 'children'> = ctaLink
    ? { page: ctaLink }
    : { href: '#' };

  return (
    <div className="bg-white mx-auto max-w-screen-xl">
      <div className="px-8 py-20 mx-auto flex flex-wrap flex-col md:flex-row items-start">
        <div className="flex flex-col w-full md:w-3/6 justify-center items-start">
          <h1 className="pt-4 text-3xl font-medium leading-tight text-gray-900">{title}</h1>
          <div className="leading-relaxed text-lg text-gray-700 py-6">{textComp}</div>
          <Link {...linkProps}>
            <a className="w-full md:w-auto bg-blue-600 text-white font-semibold rounded-full px-3 py-2 text-center">
              {ctaText}
            </a>
          </Link>
        </div>
        <div className="w-full md:w-3/6 text-center py-8 md:py-0">
          <img className="w-full px-8 z-50 float-right" src={`${image.fields.file.url}?w=960`} />
        </div>
      </div>
    </div>
  );
}
Example #22
Source File: makeCommonConsumer.ts    From ke with MIT License 6 votes vote down vote up
/**
 * Создаёт полиморфный компонент, получающий данные из контекстов и пробрасывающий
 * их в целевой. Если указать proxy функцию, то данные будут предварительно
 * обработаны через неё.
 *
 * @example
 * ```
 * const contexts = {{
 *   first: createContext(false),
 *   second: createContext(10)
 * }}
 *
 * const ConsumerFirstSecond = makeCommonConsumer(contexts, ({ first, second}) => ({ a: first, b: second }))
 * const ComponentABC: FC<{a: boolean, b: number, c: string}> = ...
 *
 * // <ConsumerFirstSecond as={ComponentABC} c="test" />
 * ```
 *
 * @param contexts - словарь контекстов для подписки
 * @param proxy - коллбэк для преобразования данных из контекстов в props итогового
 * компонента
 */
export function makeCommonConsumer<Contexts extends ContextsRecord, ConsumerProps = ContextsData<Contexts>>(
  contexts: Contexts,
  proxy?: (data: ContextsData<Contexts>) => ConsumerProps
): PolymorphComponent<ConsumerProps> {
  return ({ children, as, ...props }) => {
    const contextData = getContextsData(contexts)

    const dataProps = proxy ? proxy(contextData) : contextData

    return createElement(as, { ...props, ...dataProps } as unknown as ComponentProps<typeof as>, children)
  }
}
Example #23
Source File: proxyIntegratorRoot.ts    From ke with MIT License 6 votes vote down vote up
export function proxyIntegratorRoot<BaseRoot extends ComponentType<any>, Inners extends InnerComponents, ProxyProps>(
  base: Integrator<BaseRoot, Inners>,
  proxy: (props: ProxyProps) => ComponentProps<BaseRoot>
): Integrator<FC<ProxyProps>, Inners> {
  const newRoot: FC<ProxyProps> = (props) => createElement(base, proxy(props))

  Object.entries(base).forEach(([key, value]) => {
    ;(newRoot as Integrator<FC<ProxyProps>, Inners>)[key as keyof Inners] = value
  })

  return newRoot as Integrator<FC<ProxyProps>, Inners>
}
Example #24
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 #25
Source File: PermissionedRoute.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
PermissionedRoute = (
  props: ComponentProps<typeof Route> & {
    errorComponent?: ReactElement | null;
  } & (
      | {
          permission: Exclude<Permission, ResourcePermission>;
          resourceRef?: never;
        }
      | {
          permission: ResourcePermission;
          resourceRef: string | undefined;
        }
    ),
) => {
  const { permission, resourceRef, errorComponent, ...otherProps } = props;

  const permissionResult = usePermission(
    isResourcePermission(permission)
      ? { permission, resourceRef }
      : { permission },
  );
  const app = useApp();
  const { NotFoundErrorPage } = app.getComponents();

  let shownElement: ReactElement | null | undefined =
    errorComponent === undefined ? <NotFoundErrorPage /> : errorComponent;

  if (permissionResult.loading) {
    shownElement = null;
  } else if (permissionResult.allowed) {
    shownElement = props.element;
  }

  return <Route {...otherProps} element={shownElement} />;
}
Example #26
Source File: Items.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
SidebarScrollWrapper = styled('div')(({ theme }) => {
  const scrollbarStyles = styledScrollbar(theme);
  return {
    flex: '0 1 auto',
    overflowX: 'hidden',
    // 5px space to the right of the scrollbar
    width: 'calc(100% - 5px)',
    // Display at least one item in the container
    // Question: Can this be a config/theme variable - if so, which? :/
    minHeight: '48px',
    overflowY: 'hidden',
    '@media (hover: none)': scrollbarStyles,
    '&:hover': scrollbarStyles,
  };
}) as ComponentType<ComponentProps<'div'> & StyledComponentProps<'root'>>
Example #27
Source File: index.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
BackButton = (props: ComponentProps<typeof Button>) => {
  const classes = useStyles();

  return (
    <Button variant="outlined" className={classes.button} {...props}>
      {props.children || 'Back'}
    </Button>
  );
}
Example #28
Source File: index.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
NextButton = (
  props: ComponentProps<typeof Button> & { loading?: boolean },
) => {
  const { loading, ...buttonProps } = props;
  const classes = useStyles();

  return (
    <div className={classes.wrapper}>
      <Button
        color="primary"
        variant="contained"
        {...buttonProps}
        disabled={props.disabled || props.loading}
      />
      {props.loading && (
        <CircularProgress size="1.5rem" className={classes.buttonProgress} />
      )}
      {props.loading}
    </div>
  );
}
Example #29
Source File: NativeLinearGradient.d.ts    From nlw2-proffy with MIT License 5 votes vote down vote up
export default class NativeLinearGradient extends React.Component<
  ComponentProps<typeof CommonNativeLinearGradient> // eslint-disable-line no-undef
> {}