react-i18next#useTranslation TypeScript Examples

The following examples show how to use react-i18next#useTranslation. 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: DeleteDialog.tsx    From vscode-crossnote with GNU Affero General Public License v3.0 7 votes vote down vote up
export function DeleteDialog(props: Props) {
  const { t } = useTranslation();
  const note = props.note;

  const deleteNote = useCallback((note: Note) => {
    vscode.postMessage({
      action: MessageAction.DeleteNote,
      data: note,
    });
  }, []);

  return (
    <Dialog open={props.open} onClose={props.onClose}>
      <DialogTitle>{t("delete-file-dialog/title")}</DialogTitle>
      <DialogContent>
        <DialogContentText>
          {t("delete-file-dialog/subtitle")}
        </DialogContentText>
      </DialogContent>
      <DialogActions>
        <Button
          style={{ color: "red" }}
          onClick={() => {
            deleteNote(note);
            props.onClose();
          }}
        >
          {t("general/Delete")}
        </Button>
        <Button onClick={props.onClose}>{t("general/cancel")}</Button>
      </DialogActions>
    </Dialog>
  );
}
Example #2
Source File: DesktopWindow.tsx    From overwolf-modern-react-boilerplate with MIT License 6 votes vote down vote up
DesktopWindow = () => {
  const { t } = useTranslation()

  return (
    <>
      <DesktopHeader />
      <div className={style.container}>
        <header className={style.header}>
          <Title color="white">
            Current Locale: <b>{t('common.language')} ?</b>
            <br />
            {t('components.desktop.header')}
          </Title>
        </header>
        <main className={style.main}>
          <Title color="white">{t('components.desktop.main')}</Title>
        </main>
        <aside className={style.aside}>
          <Title color="white">{t('components.desktop.aside')}</Title>
        </aside>
        <footer className={style.footer}>
          <Title color="white">{t('components.desktop.footer')}</Title>
        </footer>
      </div>
    </>
  )
}
Example #3
Source File: AdvancedSettings.tsx    From NewWorldMinimap with MIT License 6 votes vote down vote up
export default function AdvancedSettings(props: IProps) {
    const { classes } = useSharedSettingsStyles();
    const { t } = useTranslation();

    return <>
        <hr />
        <details>
            <summary title={t('settings.advancedTooltip')} className={classes.summary} >{t('settings.advanced')}</summary>
            <p className={classes.setting}>{t('settings.advancedTooltip')}</p>
            {props.children}
        </details>
    </>;
}
Example #4
Source File: index.tsx    From cuiswap with GNU General Public License v3.0 6 votes vote down vote up
export function SwapPoolTabs({ active }: { active: 'swap' | 'pool' }) {
  const { t } = useTranslation()
  return (
    <Tabs style={{ marginBottom: '20px' }}>
      <StyledNavLink id={`swap-nav-link`} to={'/swap'} isActive={() => active === 'swap'}>
        {t('swap')}
      </StyledNavLink>
      <StyledNavLink id={`pool-nav-link`} to={'/pool'} isActive={() => active === 'pool'}>
        {t('pool')}
      </StyledNavLink>
    </Tabs>
  )
}
Example #5
Source File: index.tsx    From github-explorer with MIT License 6 votes vote down vote up
function RepositoryDetailsLayoutHeader() {
  const [t] = useTranslation();

  return (
    <Header>
      <Link to="/">
        <FiChevronLeft size={16} />
        {t("buttons.back")}
      </Link>
    </Header>
  );
}
Example #6
Source File: back.tsx    From protect-scotland with Apache License 2.0 6 votes vote down vote up
Back: FC<BackProps> = ({
  variant = 'default',
  onPress: onPressProp
}) => {
  const navigation = useNavigation();
  const {t} = useTranslation();

  const onPress = () => navigation.goBack();

  return (
    <TouchableWithoutFeedback
      accessible
      accessibilityRole="button"
      accessibilityHint={t('common:back:hint')}
      accessibilityLabel={t('common:back:label')}
      onPress={onPressProp || onPress}>
      <View style={styles.container}>
        <Image
          source={icons[variant]}
          accessibilityIgnoresInvertColors={false}
        />
      </View>
    </TouchableWithoutFeedback>
  );
}
Example #7
Source File: DAGContent.tsx    From metaflow-ui with Apache License 2.0 6 votes vote down vote up
DocstringTooltip: React.FC<{ stepName: string; docs: string }> = ({ stepName, docs }) => {
  const { t } = useTranslation();
  return (
    <>
      <StepInfoMarker
        data-tip
        data-for={stepName}
        onClick={(e) => {
          e.preventDefault();
          e.stopPropagation();
        }}
      >
        <Icon name="infoSmall" size="xs" />
        <Tooltip id={stepName}>
          <TooltipTitle>{t('run.developer-comment')}</TooltipTitle>
          {docs}
        </Tooltip>
      </StepInfoMarker>
    </>
  );
}
Example #8
Source File: filter-no-post-content-page.tsx    From microsoft-teams-apps-growyourskills with MIT License 6 votes vote down vote up
FilterNoPostContentPage: React.FunctionComponent<{}> = props => {
    const localize = useTranslation().t;

    return (
        <div className="no-post-added-container">
            <div className="app-logo">
                <EyeIcon size="largest" />
            </div>
            <div className="no-data-preview">
                <Text content={localize("noDataPreviewNote")} />
            </div>
        </div>
    )
}
Example #9
Source File: ErrorPage.tsx    From rari-dApp with GNU Affero General Public License v3.0 6 votes vote down vote up
ErrorPage: React.FC<FallbackProps> = ({ error }) => {
  const { t } = useTranslation();

  return (
    <Box color="white">
      <Box bg="red.600" width="100%" p={4}>
        <Heading>{t("Whoops! Looks like something went wrong!")}</Heading>
        <Text>
          {t(
            "You can either reload the page, or report this error to us on our"
          )}{" "}
          <Link isExternal href="https://github.com/Rari-Capital/rari-dApp">
            <u>GitHub</u>
            <ExternalLinkIcon mx="2px" />
          </Link>
        </Text>
      </Box>

      <Code colorScheme="red">{error.toString()}</Code>
    </Box>
  );
}
Example #10
Source File: index.tsx    From vscode-crossnote with GNU Affero General Public License v3.0 5 votes vote down vote up
function KanbanColumnHeaderDisplay(props: KanbanColumnHeaderProps) {
  const classes = useStyles(props);
  const { t } = useTranslation();
  const column = props.column;
  const board = props.board;
  const isPreview = props.isPreview;
  const refreshBoard = props.refreshBoard;
  const [clickedTitle, setClickedTitle] = useState<boolean>(false);
  const [titleValue, setTitleValue] = useState<string>(column.title);

  useEffect(() => {
    if (!clickedTitle && titleValue !== column.title) {
      column.title = titleValue || t("general/Untitled");
      setTitleValue(column.title);
      refreshBoard(board);
    }
  }, [clickedTitle, board, column.title, titleValue, t, refreshBoard]);

  return (
    <Box className={clsx(classes.columnHeader)}>
      <Box>
        {clickedTitle ? (
          <TextField
            value={titleValue}
            onChange={(event) => {
              setTitleValue(event.target.value);
            }}
            onBlur={() => {
              setClickedTitle(false);
            }}
            onKeyUp={(event) => {
              if (event.which === 13) {
                setClickedTitle(false);
              }
            }}
          ></TextField>
        ) : (
          <Typography
            variant={"body1"}
            style={{ cursor: "text" }}
            onClick={() => {
              if (!isPreview) {
                setClickedTitle(true);
              }
            }}
          >
            {titleValue}
          </Typography>
        )}
      </Box>
      {!isPreview && (
        <Box>
          <IconButton
            onClick={() => {
              const card: KanbanCard = {
                id: Date.now(),
                title: "", //"Card " + column.cards.length,
                description: t("general/empty"),
              };
              if (column) {
                column.cards.push(card);
              }
              props.refreshBoard(board);
            }}
          >
            <CardPlus></CardPlus>
          </IconButton>
          <IconButton
            onClick={() => {
              board.columns = board.columns.filter((l) => column.id !== l.id);
              props.refreshBoard(board);
            }}
          >
            <Close></Close>
          </IconButton>
        </Box>
      )}
    </Box>
  );
}
Example #11
Source File: AppSettings.tsx    From NewWorldMinimap with MIT License 5 votes vote down vote up
export default function AppSettings(props: IProps) {
    const {
        onClose,
        visible,
    } = props;
    const context = useContext(AppContext);
    const { classes } = useStyles();
    const { t } = useTranslation();

    const settingsPages = [...getSettingsPages()];

    const [currentPage, setCurrentPage] = useState(settingsPages[0]);
    const [isPeeking, setIsPeeking] = useState(false);

    function updateSimpleSetting<TKey extends keyof SimpleStorageSetting>(key: TKey, value: SimpleStorageSetting[TKey]) {
        store(key, value);
        context.update({ [key]: value });
    }

    const rootClassName = clsx(
        classes.root,
        !visible && classes.hidden,
        context.settings.showHeader && classes.belowHeader,
        isPeeking && context.gameRunning && classes.peek);

    const tooSmallMessageClassName = clsx(
        classes.tooSmallMessage,
        !visible && classes.hidden,
        context.settings.showHeader && classes.belowHeader,
        isPeeking && context.gameRunning && classes.peek);

    const pageProps: IAppSettingsPageProps = {
        settings: context.settings,
        updateSimpleSetting,
        updateSettings: context.update,
        setPeek: setIsPeeking,
    };

    const PageComponent = settingsPageMap[currentPage];

    return <>
        <div className={rootClassName}>
            <button className={classes.close} onClick={onClose} title={t('close')}>
                <CloseOIcon />
            </button>
            <h2 className={classes.title}>{t('settings.title')}</h2>
            <nav className={classes.nav}>
                {settingsPages.map(p =>
                    <button
                        key={p}
                        className={clsx(classes.navItem, p === currentPage && classes.navItemActive)}
                        onClick={() => setCurrentPage(p)}
                    >
                        {t(`settings.${p}._`)}
                    </button>
                )}
            </nav>
            <div className={classes.content}>
                <PageComponent {...pageProps} />
            </div>
            <footer className={classes.footer}>
                <span>{t('settings.open')}</span>
                <span className={classes.bottomRightMenu}>
                    <DiscordButton />
                    <LanguagePicker />
                </span>
            </footer>
        </div>
        <div className={tooSmallMessageClassName}>
            <span>{t('settings.tooSmall')}</span>
        </div>
    </>;
}
Example #12
Source File: index.tsx    From cuiswap with GNU General Public License v3.0 5 votes vote down vote up
export default function Web3ReactManager({ children }) {
  const { t } = useTranslation()
  const { active } = useWeb3React()
  const { active: networkActive, error: networkError, activate: activateNetwork } = useWeb3React(NetworkContextName)

  // try to eagerly connect to an injected provider, if it exists and has granted access already
  const triedEager = useEagerConnect()

  // after eagerly trying injected, if the network connect ever isn't active or in an error state, activate itd
  useEffect(() => {
    if (triedEager && !networkActive && !networkError && !active) {
      activateNetwork(network)
    }
  }, [triedEager, networkActive, networkError, activateNetwork, active])

  // when there's no account connected, react to logins (broadly speaking) on the injected provider, if it exists
  useInactiveListener(!triedEager)

  // handle delayed loader state
  const [showLoader, setShowLoader] = useState(false)
  useEffect(() => {
    const timeout = setTimeout(() => {
      setShowLoader(true)
    }, 600)

    return () => {
      clearTimeout(timeout)
    }
  }, [])

  // on page load, do nothing until we've tried to connect to the injected connector
  if (!triedEager) {
    return null
  }

  // if the account context isn't active, and there's an error on the network context, it's an irrecoverable error
  if (!active && networkError) {
    return (
      <MessageWrapper>
        <Message>{t('unknownError')}</Message>
      </MessageWrapper>
    )
  }

  // if neither context is active, spin
  if (!active && !networkActive) {
    return showLoader ? (
      <MessageWrapper>
        <Loader />
      </MessageWrapper>
    ) : null
  }

  return children
}
Example #13
Source File: index.ts    From github-explorer with MIT License 5 votes vote down vote up
export function useRepositories() {
  const [
    repositories,
    setRepositories,
  ] = useLocalStorage<Repository[]>(REPOSITORIES_STORAGE_KEY, []);

  const [isLoading, setIsLoading] = useState(false);

  const [t] = useTranslation();

  const addRepository = useCallback(async (repositoryName: string) => {
    const findRepositoryWithTheSameName = repositories.find(
      repository => repositoryName === repository.full_name,
    );

    if (findRepositoryWithTheSameName) {
      throw new Error(t("errors.this_repository_has_already_been_added"));
    }

    try {
      setIsLoading(true);

      const repository = await getRepository(repositoryName);

      setRepositories([
        repository,
        ...repositories,
      ]);
    } catch (err) {
      throw new Error(t("errors.the_repository_could_not_be_found"));
    } finally {
      setIsLoading(false);
    }
  }, [
    t,
    repositories,
    setRepositories,
  ]);

  const payload = useMemo(() => ({
    isLoading,
    repositories,
    addRepository,
  }), [
    isLoading,
    repositories,
    addRepository,
  ]);

  return payload;
}
Example #14
Source File: go-to-settings.tsx    From protect-scotland with Apache License 2.0 5 votes vote down vote up
GoToSettings: FC = () => {
  const {t} = useTranslation();
  const {status, askPermissions, isAuthorised} = useExposure();
  const platform = Platform.OS === 'ios' ? 'ios' : 'android';

  const bluetoothDisabled =
    status.state === StatusState.disabled &&
    status.type?.includes(StatusType.bluetooth);

  const ensUnknown = status.state === StatusState.unknown;
  const ensDisabled = status.state === StatusState.disabled;
  const notAuthorised = isAuthorised === AuthorisedStatus.unknown;

  return (
    <Button
      variant="dark"
      rounded
      onPress={async () =>
        ensUnknown || notAuthorised
          ? await askPermissions()
          : goToSettingsAction(bluetoothDisabled, askPermissions)
      }
      label={
        ensUnknown || notAuthorised
          ? t('common:turnOnBtnLabel')
          : ensDisabled
          ? t('common:turnOnBtnLabel')
          : platform === 'android'
          ? t('common:turnOnBtnLabel')
          : t('common:goToSettings')
      }
      hint={
        ensUnknown || notAuthorised
          ? t('common:turnOnBtnHint')
          : ensDisabled
          ? t('common:turnOnBtnHint')
          : platform === 'android'
          ? t('common:turnOnBtnHint')
          : t('common:goToSettingsHint')
      }>
      {ensUnknown || notAuthorised
        ? t('common:turnOnBtnLabel')
        : ensDisabled
        ? t('common:turnOnBtnLabel')
        : platform === 'android'
        ? t('common:turnOnBtnLabel')
        : t('common:goToSettings')}
    </Button>
  );
}
Example #15
Source File: App.tsx    From metaflow-ui with Apache License 2.0 5 votes vote down vote up
App: React.FC = () => {
  const { t } = useTranslation();
  // Features list must be fetched before we render application so we don't render things that
  // are disabled by backend service.
  const [flagsReceived, setFlagsReceived] = useState(false);

  useEffect(() => {
    // Get info about backend versions.
    fetchServiceVersion();
    // Get info about features that are enabled by server
    fetchFeaturesConfig(() => setFlagsReceived(true));
  }, []);

  return (
    <ThemeProvider theme={theme}>
      <ErrorBoundary message={t('error.application-error')}>
        <NotificationsProvider>
          <TimezoneProvider>
            <PluginsProvider>
              <LoggingProvider>
                <GlobalStyle />
                <Router>
                  <QueryParamProvider ReactRouterRoute={Route}>
                    {flagsReceived ? (
                      <>
                        <Notifications />
                        <Announcements />
                        <AppBar />
                        <Page>
                          <Root />
                        </Page>
                        <Logger />
                      </>
                    ) : (
                      <FeatureFlagLoader />
                    )}
                  </QueryParamProvider>
                </Router>
              </LoggingProvider>
              <PluginRegisterSystem />
            </PluginsProvider>
          </TimezoneProvider>
        </NotificationsProvider>
      </ErrorBoundary>
    </ThemeProvider>
  );
}
Example #16
Source File: command-bar.tsx    From microsoft-teams-apps-growyourskills with MIT License 5 votes vote down vote up
CommandBar: React.FunctionComponent<ICommandBarProps> = props => {
    const localize = useTranslation().t;
    initializeIcons();
    /**
	* Invokes for key press
	* @param event Object containing event details
	*/
    const onTagKeyDown = (event: any) => {
        if (event.key === 'Enter') {
            props.searchFilterProjectsUsingAPI();
        }
    }

    return (
        <Flex gap="gap.small" vAlign="center" hAlign="end" className="command-bar-wrapper">
            {props.showFilter ?
                <>
                    <Flex.Item push>
                        <Button
                            className="filter-button sdfsdf"
                            icon={
                                props.showSolidFilterIcon ?
                                    <Icon iconName="FilterSolid" className="filter-icon-filled" /> :
                                    <Icon iconName="Filter" className="filter-icon" />
                            }
                            content={
                                <Text content={localize("filter")} className={props.showSolidFilterIcon ? "filter-icon-filled" : ""} />
                            }
                            text
                            onClick={props.onFilterButtonClick} />
                    </Flex.Item>

                    <div className="search-bar-wrapper">
                        <Input icon={<SearchIcon styles={{ display: "none" }} />} inverted fluid onKeyDown={onTagKeyDown} onChange={(event: any) => props.onSearchInputChange(event.target.value)} value={props.commandBarSearchText} placeholder={localize("searchPlaceholder")} />
                        <SearchIcon key="search" onClick={(event: any) => props.searchFilterProjectsUsingAPI()} className="discover-search-icon" />
                    </div>
                    {
                        props.teamId === "" || props.teamId === undefined || props.teamId === null
                            ?
                            <NewProjectDialog projectDetails={props.projectDetails} onSubmit={props.onNewProjectSubmit} />
                            :
                            <></> 
                    }
                    
                </> : <></>
            }
        </Flex>
    );
}
Example #17
Source File: Web3ReactManager.tsx    From interface-v2 with GNU General Public License v3.0 5 votes vote down vote up
Web3ReactManager: React.FC<{ children: JSX.Element }> = ({
  children,
}) => {
  const { t } = useTranslation();
  const classes = useStyles();
  const { active } = useWeb3React();
  const {
    active: networkActive,
    error: networkError,
    activate: activateNetwork,
  } = useWeb3React(GlobalConst.utils.NetworkContextName);

  // try to eagerly connect to an injected provider, if it exists and has granted access already
  const triedEager = useEagerConnect();

  // after eagerly trying injected, if the network connect ever isn't active or in an error state, activate itd
  useEffect(() => {
    if (triedEager && !networkActive && !networkError && !active) {
      activateNetwork(network);
    }
  }, [triedEager, networkActive, networkError, activateNetwork, active]);

  // when there's no account connected, react to logins (broadly speaking) on the injected provider, if it exists
  useInactiveListener(!triedEager);

  // handle delayed loader state
  const [showLoader, setShowLoader] = useState(false);
  useEffect(() => {
    const timeout = setTimeout(() => {
      setShowLoader(true);
    }, 600);

    return () => {
      clearTimeout(timeout);
    };
  }, []);

  // on page load, do nothing until we've tried to connect to the injected connector
  if (!triedEager) {
    return null;
  }

  // if the account context isn't active, and there's an error on the network context, it's an irrecoverable error
  if (!active && networkError) {
    return (
      <Box className={classes.messageWrapper}>
        <Typography className={classes.message}>{t('unknownError')}</Typography>
      </Box>
    );
  }

  // if neither context is active, spin
  if (!active && !networkActive) {
    return showLoader ? (
      <Box className={classes.messageWrapper}>
        <CircularProgress />
      </Box>
    ) : null;
  }

  return children;
}
Example #18
Source File: FuseLiquidationsPage.tsx    From rari-dApp with GNU Affero General Public License v3.0 5 votes vote down vote up
LiquidationEventsList = ({
  liquidations,
  totalLiquidations,
  setLiquidationsToShow,
}: {
  liquidations?: LiquidationEvent[];
  totalLiquidations: number;
  setLiquidationsToShow: React.Dispatch<React.SetStateAction<number>>;
}) => {
  const { t } = useTranslation();

  const isMobile = useIsMobile();

  return (
    <Column
      mainAxisAlignment="flex-start"
      crossAxisAlignment="flex-start"
      expand
    >
      <Row
        mainAxisAlignment="flex-start"
        crossAxisAlignment="center"
        height="45px"
        width="100%"
        flexShrink={0}
        pl={4}
        pr={1}
      >
        <Text fontWeight="bold" width={isMobile ? "100%" : "30%"}>
          {t("Recent Liquidations")}
        </Text>

        {isMobile ? null : (
          <>
            <Text fontWeight="bold" textAlign="center" width="23%">
              {t("Collateral Seized")}
            </Text>

            <Text fontWeight="bold" textAlign="center" width="23%">
              {t("Borrow Repaid")}
            </Text>

            <Text fontWeight="bold" textAlign="center" width="25%">
              {t("Timestamp")}
            </Text>
          </>
        )}
      </Row>

      <ModalDivider />

      <Column
        mainAxisAlignment="flex-start"
        crossAxisAlignment="center"
        width="100%"
      >
        {liquidations ? (
          <>
            {liquidations.map((liquidation, index) => {
              return (
                <LiquidationRow
                  key={liquidation.transactionHash}
                  liquidation={liquidation}
                  noBottomDivider={index === liquidations.length - 1}
                />
              );
            })}

            <RowsControl
              totalAmount={totalLiquidations}
              setAmountToShow={setLiquidationsToShow}
            />
          </>
        ) : (
          <Spinner my={8} />
        )}
      </Column>
    </Column>
  );
}