react#FunctionComponent TypeScript Examples

The following examples show how to use react#FunctionComponent. 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: index.tsx    From ExpressLRS-Configurator with GNU General Public License v3.0 7 votes vote down vote up
CardTitle: FunctionComponent<CardTitleProps> = memo(({ icon, title }) => {
  return (
    <CardContent>
      <Grid container spacing={1} alignItems="center">
        <Grid item>{icon}</Grid>
        <Grid item flexGrow={1}>
          <Typography variant="h6">{title}</Typography>
        </Grid>
      </Grid>
    </CardContent>
  );
})
Example #2
Source File: Collapsible.tsx    From GTAV-NativeDB with MIT License 6 votes vote down vote up
Collapsible: FunctionComponent<CollapsibleProps> = ({ children, label, variant, fullWidth }) => {
  const [open, setOpen] = useState(false)

  const toggle = useCallback(() => {
    setOpen(!open)
  }, [open, setOpen])

  return (
    <Fragment>
      <Button 
        variant={variant} 
        fullWidth={fullWidth} 
        onClick={toggle}
      >
        {label}
      </Button>
      <Collapse in={open}>
        {children}
      </Collapse>
    </Fragment>
  )
}
Example #3
Source File: AppRouter.tsx    From react-tutorials with MIT License 6 votes vote down vote up
AppRouter: FunctionComponent = () => {
  return (
    <Router>
      <RecoilRoot>
        <Suspense fallback={<span>Loading...</span>}>
          <Switch>
            <Route exact path="/" component={App} />
          </Switch>
        </Suspense>
      </RecoilRoot>
    </Router>
  )
}
Example #4
Source File: markdown-functions.tsx    From keycaplendar with MIT License 6 votes vote down vote up
componentBuilder = (name: string, Component: FunctionComponent) =>
  Object.assign(
    ({
      /* eslint-disable @typescript-eslint/no-unused-vars */
      inline,
      isHeader,
      level,
      node,
      ordered,
      /* eslint-enable @typescript-eslint/no-unused-vars */
      ...props
    }: Record<string, any>) => <Component {...props} />,
    { displayName: `Custom ${name}` }
  )
Example #5
Source File: index.tsx    From ExpressLRS-Configurator with GNU General Public License v3.0 6 votes vote down vote up
DocumentationLink: FunctionComponent<DocumentationLinkProps> = ({
  children,
  url,
  firmwareVersion,
}) => {
  const href = toUrl(firmwareVersion, url);
  return (
    <a target="_blank" rel="noreferrer noreferrer" href={href}>
      {children}
    </a>
  );
}
Example #6
Source File: PrimaryButton.tsx    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
PrimaryButton: FunctionComponent<PrimaryButtonProps> = ({ onPress, loading, style, disabled, children }) => {
  return (
    <View style={style}>
      <TouchableOpacity style={[
                          styles.button,
                          disabled && {opacity: 0.5}
                        ]}
                        onPress={onPress}
                        disabled={disabled}
      >
        {loading ? (
          <ActivityIndicator color={colors.textInverted}/>
        ) : (
          <Text style={styles.text}>{children}</Text>
        )}
      </TouchableOpacity>
    </View>
  );
}
Example #7
Source File: Map.tsx    From MLH-Fellow-Map with MIT License 6 votes vote down vote up
Map: FunctionComponent<{
  defaultBaseMap: string;
  className?: string;
}> = ({
  children,
  className,
  defaultBaseMap = DEFAULT_MAP_SERVICE,
  ...rest
}) => {
  useConfigureLeaflet();

  const basemap = getMapServiceByName(defaultBaseMap);

  const mapClassName = `map`;

  if (!isDomAvailable()) {
    return (
      <div className={`${mapClassName} ${className || ''}`}>
        <p className="map-loading">Loading map...</p>
      </div>
    );
  }

  const mapSettings = {
    className: 'map-base',
    zoomControl: false,
    ...rest,
  };

  return (
    <div className={mapClassName}>
      <BaseMap {...mapSettings}>
        {basemap && <TileLayer {...basemap} />}
        {children}
        <ZoomControl position="bottomright" />
      </BaseMap>
    </div>
  );
}
Example #8
Source File: DrawerItem.tsx    From hamagen-react-native with MIT License 6 votes vote down vote up
DrawerItem: FunctionComponent<Props> = ({ isRTL, icon, iconSize= 18, label, style, onPress, children }) => {
  const LabelComponent = useMemo(() => {
    if (React.isValidElement(label)) {
      return label
    } else if (typeof label === 'string') {
      return <Text style={styles.label}>{label}</Text>
    }
    return null
  },[label])
  
  


  return (
    <TouchableOpacity style={[styles.container, { flexDirection: isRTL ? 'row-reverse' : 'row' }, style]} onPress={onPress}>
      <Icon source={icon} width={iconSize} />
      {LabelComponent}
    </TouchableOpacity>

  );
}
Example #9
Source File: AgeChart.tsx    From crowdsource-dataplatform with MIT License 6 votes vote down vote up
AgeChart: FunctionComponent<AgeChartProps> = ({ language }) => {
  const { t } = useTranslation();
  const jsonUrl = language ? apiPaths.ageGroupAndLanguageContributions : apiPaths.ageGroupContributions;
  const { data: jsonData, isValidating } = useFetch<Array<AgeGroupAndLanguageContributions>>(jsonUrl);
  let ageData = language ? jsonData?.filter(d => d.language === language) : jsonData;

  let chartData: Array<Object> = [];

  AGE_GROUP_CONFIG.forEach(ageConfig => {
    const data = ageData?.filter(d => d.age_group === ageConfig.value)[0];
    if (data) {
      chartData.push({
        category: t(ageConfig.key),
        value: data.speakers || 0,
      });
    }
  });

  return (
    <div className="bg-light rounded-8 p-5 p-md-8 h-100">
      <p className="mb-5 display-2">{t(chartTitle)}</p>
      <div className={styles.chart}>
        {!jsonData || isValidating ? (
          <div className="d-flex justify-content-center align-items-center h-100 w-100">
            <Spinner data-testid="ChartSpinner" animation="border" variant="primary" />
          </div>
        ) : (
          <PieChart
            id="pie_chart"
            data={{
              data: chartData,
              colors: ['#85A8F9', '#B7D0FE', '#6C85CE', '#316AFF', '#294691'],
            }}
          />
        )}
      </div>
    </div>
  );
}
Example #10
Source File: DropdownInput.tsx    From ow-mod-manager with MIT License 6 votes vote down vote up
DropdownInput: FunctionComponent<Props> = ({
  value,
  onChange,
  label,
  disabled,
  tooltip = '',
}) => {
  const [mainLabel, falseLabel, trueLabel] = label.split('|');

  return (
    <Tooltip title={tooltip} placement="bottom">
      <ListItem disabled={disabled}>
        <Box mr={2}>
          <Typography>{mainLabel}</Typography>
        </Box>
        <Select
          variant="outlined"
          margin="dense"
          color="secondary"
          value={value ? 'true' : 'false'}
          onChange={(event) => {
            event.preventDefault();
            onChange(event.target.value === 'true');
          }}
        >
          <MenuItem value="false">{falseLabel}</MenuItem>
          <MenuItem value="true">{trueLabel}</MenuItem>
        </Select>
      </ListItem>
    </Tooltip>
  );
}
Example #11
Source File: _app.tsx    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
_app: FunctionComponent<AppProps> = ({ Component, pageProps }) => {
  // TODO: Remove server-side JSS styles.
  // Normally you'd call 'useEffect' to call jssStyles.parentElement.removeChild(jssStyles);
  // However, I was experiencing an unknown bug where the old class names weren't being replaced
  // with the new ones, so I just got rid of the call so that the old class names would work.

  return (
    <>
      {/* StoreProvider allows hooks and components to access the Redux store. */}
      <StoreProvider store={store}>
        {/* ThemeProvider allows for child components to access the Material UI theme. */}
        <ThemeProvider theme={Theme}>
          {/* CSSBaseline injects a basic cascading style sheet for use by Material UI styling. */}
          <CssBaseline />
          {/* NotificationProvider handles the Notistack.
              Must be a child of StoreProvider since Redux handles notifications. */}
          <StylesProvider generateClassName={generateClassName}>
            <NotificationProvider>
              {/* ErrorHandler provides a fallback interface to use if the web page crashes. */}
              <ErrorHandler errorHandler={FullPageErrorHandler}>
                {/* Component provides the actual map content. */}
                <Component {...pageProps} />
              </ErrorHandler>
            </NotificationProvider>
          </StylesProvider>
        </ThemeProvider>
      </StoreProvider>
    </>
  );
}
Example #12
Source File: nodes.tsx    From react-carousel with MIT License 6 votes vote down vote up
dynamicCarouselItemNodes = () => {
	const Component: FunctionComponent<DynamicCarouselItemNodesProps> = ({
		id,
	}: DynamicCarouselItemNodesProps) => {
		const [state, setstate] = useState(0);
		return (
			<button key={id} onClick={() => setstate(state + 1)}>
				{state}
			</button>
		);
	};

	return [
		<Component id={1} />,
		<Component id={2} />,
		<Component id={3} />,
		<Component id={4} />,
	];
}
Example #13
Source File: component.tsx    From react-loosely-lazy with Apache License 2.0 6 votes vote down vote up
private DynamicFallback: FunctionComponent<DynamicFallbackProps> = ({
    children,
    outsideSuspense,
  }) => {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    useLayoutEffect(() => {
      return () => {
        // the effect cleanup is called by the Suspense boundary itself
        // when both Lazy AND the eventual promises thrown are done
        // so Suspense will re-render with actual content and we remove
        // the hydration fallback at the same time
        if (!outsideSuspense) this.state.setFallback(null);
      };
    }, [outsideSuspense]);

    return outsideSuspense
      ? children(this.hydrationFallback ? this.hydrationFallback : null)
      : children(this.hydrationFallback ? null : this.props.fallback);
  };
Example #14
Source File: inputButton.tsx    From grafana-weathermap-panel with Apache License 2.0 6 votes vote down vote up
InputButtonField: FunctionComponent<InputButtonFieldProps> = ({ label, value, name, required, _handleChange, id, withLabel }) => {
  if (withLabel === true) {
    return (
      <div>
        <FormField
          label={label}
          labelWidth={10}
          inputWidth={20}
          type="button"
          required={required}
          name={name}
          id={id}
          onClick={_handleChange}
          value={label || ''}
        />
      </div>
    );
  } else {
    return (
      <div>
        <Button onClick={_handleChange} variant="danger" id={id} size="md">
          Delete
        </Button>
        {/* <FormField label={''}
								inputWidth={20}
								type='button'
								required={required}
								name={name}
								id={id}
								onClick={_handleChange}
								value={label || ''} /> */}
      </div>
    );
  }
}
Example #15
Source File: Card.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
Card: FunctionComponent<Props> = (props: PropsWithChildren<Props>) => {
  const {
    title,
    createdAt,
    updatedAt,
    prUrl,
    authorName,
    authorAvatar,
    repositoryName,
    children,
  } = props;

  return (
    <Box marginBottom={1}>
      <Paper variant="outlined">
        <CardActionArea href={prUrl} target="_blank">
          <Box padding={1}>
            <CardHeader
              title={title}
              createdAt={createdAt}
              updatedAt={updatedAt}
              authorName={authorName}
              authorAvatar={authorAvatar}
              repositoryName={repositoryName}
            />
            {children}
          </Box>
        </CardActionArea>
      </Paper>
    </Box>
  );
}
Example #16
Source File: index.tsx    From ExpressLRS-Configurator with GNU General Public License v3.0 5 votes vote down vote up
BuildNotificationsList: FunctionComponent<BuildNotificationsListProps> = memo(
  ({ notifications }) => {
    const toSeverity = (
      item: BuildProgressNotificationType
    ): 'error' | 'info' | 'success' => {
      switch (item) {
        case BuildProgressNotificationType.Error:
          return 'error';
        case BuildProgressNotificationType.Info:
          return 'info';
        case BuildProgressNotificationType.Success:
          return 'success';
        default:
          return 'info';
      }
    };
    // TODO: this should be used for translations
    const toText = (step: BuildFirmwareStep): string => {
      switch (step) {
        case BuildFirmwareStep.VERIFYING_BUILD_SYSTEM:
          return 'Verifying build system';
        case BuildFirmwareStep.DOWNLOADING_FIRMWARE:
          return 'Downloading firmware';
        case BuildFirmwareStep.BUILDING_USER_DEFINES:
          return 'Building user_defines.txt';
        case BuildFirmwareStep.BUILDING_FIRMWARE:
          return 'Compiling firmware';
        case BuildFirmwareStep.FLASHING_FIRMWARE:
          return 'Flashing device';
        default:
          return '';
      }
    };
    return (
      <>
        {notifications.map((item, idx) => {
          return (
            <React.Fragment key={`${idx}-${item.step}`}>
              <Alert sx={styles.notification} severity={toSeverity(item.type)}>
                {item?.step !== undefined &&
                  item.step !== null &&
                  toText(item.step)}
              </Alert>
            </React.Fragment>
          );
        })}
      </>
    );
  }
)