react-intl#useIntl TypeScript Examples

The following examples show how to use react-intl#useIntl. 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: LanguageSwitcher.tsx    From jmix-frontend with Apache License 2.0 7 votes vote down vote up
LanguageSwitcher = observer((props: LanguageSwitcherProps) => {
  const intl = useIntl();
  const mainStore = useMainStore();

  const handleChange = useCallback(
    (locale: string) => runInAction(() => (mainStore.locale = locale)),
    [mainStore]
  );

  if (localesStore.localesInfo.length === 1) {
    return null; // Do not show LanguageSwitcher if there is only a single locale option
  }

  return (
    <Select
      defaultValue={mainStore.locale ?? undefined}
      onChange={handleChange}
      size="small"
      style={props.style}
      bordered={false}
      className={props.className}
      dropdownMatchSelectWidth={false}
      aria-label={intl.formatMessage({ id: "a11y.select.LanguageSwitcher" })}
    >
      {localesStore.localesInfo.map(({ locale, caption }) => (
        <Select.Option key={locale} value={locale}>
          {caption}
        </Select.Option>
      ))}
    </Select>
  );
})
Example #2
Source File: useLocale.ts    From react-starter-boilerplate with MIT License 6 votes vote down vote up
useLocale = (): IntlShape & LocaleContextValueType => {
  const intl = useIntl();
  const localeContext = useContext(LocaleContext);

  if (localeContext === undefined) {
    throw new Error('LocaleContext is unavailable, make sure you are using LocaleContextController');
  }

  const locale = useMemo(
    () => ({
      ...intl,
      ...localeContext,
    }),
    [intl, localeContext],
  );

  return locale;
}
Example #3
Source File: index.tsx    From strapi-plugin-comments with MIT License 6 votes vote down vote up
DiscussionThreadItemFooter = ({
  children,
  author,
  createdAt,
  updatedAt,
}) => {
  const { formatDate } = useIntl();

  const dateTime = formatDate(updatedAt || createdAt, {
    dateStyle: "medium",
    timeStyle: "short",
  });
  const { name, avatar } = author || {};

  return (
    <DiscussionThreadItemFooterStyled as={Box} paddingTop={2} direction="row">
      <DiscussionThreadItemFooterMeta size={3} horizontal>
        { author && (<UserAvatar avatar={avatar} name={name} />) }
        <Typography variant="pi" fontWeight="bold" textColor="neutral800">
          {name || getMessage('compontents.author.unknown')}
        </Typography>
        <Typography variant="pi" textColor="neutral600">
          {dateTime}
        </Typography>
      </DiscussionThreadItemFooterMeta>
      {children}
    </DiscussionThreadItemFooterStyled>
  );
}
Example #4
Source File: useTranslate.tsx    From amazon-chime-live-events with Apache License 2.0 6 votes vote down vote up
function useTranslate(id?: string, values?: any) {
  const intl = useIntl();

  if (id) {
    return intl.formatMessage(
      {
        id,
      },
      values
    );
  }

  return (contentId: string, contentValues?: any) =>
    intl.formatMessage({ id: contentId }, contentValues);
}
Example #5
Source File: index.tsx    From ever-wallet-browser-extension with GNU General Public License v3.0 6 votes vote down vote up
export function NewSeedPhrase({ seedWords, onNext, onBack }: Props): JSX.Element {
    const intl = useIntl()
    return (
        <div className="accounts-management">
            <header className="accounts-management__header">
                <h2 className="accounts-management__header-title">
                    {intl.formatMessage({ id: 'ADD_SEED_PANEL_SAVE_HEADER' })}
                </h2>
            </header>

            <div className="accounts-management__wrapper">
                <div className="accounts-management__content">
                    <ol>
                        {seedWords?.map((word) => (
                            <li key={word} className="accounts-management__content-word">
                                {word.toLowerCase()}
                            </li>
                        ))}
                    </ol>
                </div>

                <footer className="accounts-management__footer">
                    <div className="accounts-management__footer-button-back">
                        <Button
                            text={intl.formatMessage({ id: 'BACK_BTN_TEXT' })}
                            white
                            onClick={onBack}
                        />
                    </div>
                    <Button
                        text={intl.formatMessage({ id: 'WROTE_ON_PAPER_BTN_TEXT' })}
                        onClick={onNext}
                    />
                </footer>
            </div>
        </div>
    )
}
Example #6
Source File: login.view.tsx    From malagu with MIT License 6 votes vote down vote up
export function Login() {
    const location = useLocation();
    const size = useContext(ResponsiveContext);
    const intl = useIntl();
    const targetUrlParameter = ConfigUtil.get<string>('malagu.security.targetUrlParameter');
    const registrations = ConfigUtil.get<{[key: string]: { icon?: string, clientName: string } }>('malagu.oauth2.client.registrations');
    const redirect = parse(location.search && location.search.substring(1))[targetUrlParameter];
    const queryStr = redirect ? `?${stringify({ [targetUrlParameter]: redirect})}` : '';
    return (
    <StyledWraper style={size === 'small' ? { top: 0, bottom: 0, right: 0, left: 0 } : undefined }>
        <StyledContainer size={size}>
            <Box direction="column" pad="large" align="center" background="brand" round={ size === 'small' ? undefined : { corner: 'top', size: '4px' } }>
                <Button plain
                    href={ConfigUtil.get('accounts.home.url')}
                    icon={<Icon size="large" color="white" icon={ConfigUtil.get('accounts.logo.icon')}></Icon>}>
                </Button>
                <Heading level="4" color="white">{intl.formatMessage({ id: 'accounts.logo.label' })}</Heading>
            </Box>
            <Box direction="column" align="center" animation="slideDown">
                <Heading level="6">{intl.formatMessage({ id: 'accounts.quick.login.label' })}</Heading>
                <Nav>
                    {
                        Object.keys(registrations).map(id => (
                            <Button
                                hoverIndicator
                                icon={<Icon icon={registrations[id].icon || registrations[id].clientName} size="large"></Icon>}
                                href={`/oauth2/authorization/${id}${queryStr}`}>
                            </Button>
                        ))
                    }
                </Nav>
            </Box>
            <Box direction="column" fill="horizontal" style={ { position: 'absolute', bottom: 0 } } align="center">
                <LocaleMenu size="small" fontSize="12px"/>
            </Box>
        </StyledContainer>
    </StyledWraper>);

}
Example #7
Source File: BoolView.tsx    From project-loved-web with MIT License 6 votes vote down vote up
export function BoolView({ noColor, option, value }: BoolViewProps) {
  const intl = useIntl();
  let className: string | undefined;

  if (!noColor) {
    className = value ? 'success' : 'error';
  }

  return option ? (
    <option className={className} value={+value}>
      {intl.formatMessage(value ? messages.yes : messages.no)}
    </option>
  ) : (
    <span className={className}>{intl.formatMessage(value ? messages.yes : messages.no)}</span>
  );
}
Example #8
Source File: CascaderPage.tsx    From gio-design with Apache License 2.0 6 votes vote down vote up
export default function CardPage() {
  const { formatMessage } = useIntl();

  return (
    <>
      <Title>{formatMessage({ defaultMessage: 'Cascader 级联选择器' })}</Title>
      <p>
        {formatMessage({
          defaultMessage: '递进式选择器',
        })}
      </p>
      <p>Upgrading Guide</p>
      <ul>
        <li>样式变化:大改</li>
        <li>APi变化:大改</li>
        <li>dataSource变为options</li>
        <li>封装popover和list,inputbutton</li>
        <li>支持两种穿参,options和JSX</li>
        <li>Inputbutton 触发trigger,popover弹出list</li>
      </ul>
      <Heading>{formatMessage({ defaultMessage: '代码演示' })}</Heading>
      <Subheading>{formatMessage({ defaultMessage: '样例' })}</Subheading>

      <Canvas>
        <Story id="upgraded-cascader--demo" />
      </Canvas>
      <Subheading>{formatMessage({ defaultMessage: '简单结构' })}</Subheading>

      <Canvas>
        <Story id="upgraded-cascader--default" />
      </Canvas>

      <Heading>{formatMessage({ defaultMessage: '参数说明' })}</Heading>
      <ArgsTable of={Cascader} />
    </>
  );
}
Example #9
Source File: AppHeader.tsx    From jmix-frontend with Apache License 2.0 5 votes vote down vote up
AppHeader = observer(({ children }: { children?: React.ReactNode }) => {
  const intl = useIntl();
  const mainStore = useMainStore();

  const [settingsEnabled, setSettingsEnabled] = useState(false);

  const [visibleHotkeyInfo, setVisibleHotkeyInfo] = useState(false);

  const toggleHotkeyInfo = useCallback<KeyHandler>(
    () => setVisibleHotkeyInfo(!visibleHotkeyInfo),
    [visibleHotkeyInfo]
  );
  useHotkey(toggleHotkeyInfoHotkeyConfig, toggleHotkeyInfo);

  const toggleSettings = useCallback(() => {
    setSettingsEnabled(isEnabled => {
      return !isEnabled;
    });
  }, []);

  const showLogoutConfirm = useCallback(() => {
    modals.open({
      content: intl.formatMessage({ id: "header.logout.areYouSure" }),
      okText: intl.formatMessage({ id: "header.logout.ok" }),
      cancelText: intl.formatMessage({ id: "header.logout.cancel" }),
      onOk: () => mainStore.logout()
    });
  }, [mainStore, intl]);

  return (
    <div className={styles.header}>
      <JmixLightIcon className={styles.icon} />

      <div className={styles.content}>{children}</div>
      <>
        {settingsEnabled && (
          <>
            <ThemeSwitcher className={styles.themeSwitcher} />
            <LanguageSwitcher className={styles.languageSwitcher} />
          </>
        )}
      </>
      <Space className={styles.userPanel}>
        <span>{mainStore.userName}</span>
        <Button
          className={classNames(
            settingsEnabled ? styles.settingsBtnActive : styles.settingsBtn,
            appStyles.focusOuterHighlight
          )}
          type={"text"}
          icon={<SettingOutlined role={""} />}
          onClick={toggleSettings}
          role={"switch"}
          aria-checked={settingsEnabled}
        />
        <HotkeyInfoModalButton
          visible={visibleHotkeyInfo}
          setVisible={setVisibleHotkeyInfo}
          className={classNames(styles.infoBtn, appStyles.focusOuterHighlight)}
        />
        <Button
          id="button_logout"
          className={classNames(
            styles.logoutBtn,
            appStyles.focusOuterHighlight
          )}
          type="text"
          icon={<LogoutOutlined role={""} />}
          onClick={showLogoutConfirm}
        />
      </Space>
    </div>
  );
})
Example #10
Source File: useI18n.ts    From airtable-app-mind-flow with MIT License 5 votes vote down vote up
useFormatMessage = (): ((
  id: LocaleKey, // only accepts valid keys, not any string
  values?: Record<string, PrimitiveType>
) => string) => {
  const intl = useIntl();
  return (id, values) => intl.formatMessage({ id }, values);
}
Example #11
Source File: Seo.tsx    From test with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
Seo = () => {
  const intl = useIntl()

  const title = intl.formatMessage(messages.title)
  const description = intl.formatMessage(messages.description)

  return (
    <Helmet
      htmlAttributes={{ lang: intl.locale }}
      title={title}
      titleTemplate={`%s | ${title}`}
      meta={[
        {
          name: 'description',
          content: description,
        },
        {
          property: 'og:title',
          content: title,
        },
        {
          property: 'og:description',
          content: description,
        },
        {
          property: 'og:type',
          content: 'website',
        },
        {
          name: 'twitter:card',
          content: 'summary',
        },
        {
          name: 'twitter:title',
          content: title,
        },
        {
          name: 'twitter:description',
          content: description,
        },
      ]}
    />
  )
}
Example #12
Source File: Unsupported.tsx    From amazon-chime-live-events with Apache License 2.0 5 votes vote down vote up
Unsupported = () => {
  return (
    <Informational>
      {useIntl().formatMessage({ id: 'UnsupportedBrowser.message' })}
    </Informational>
  );
}
Example #13
Source File: ChimeSdkWrapper.ts    From amazon-chime-sdk-classroom-demo with Apache License 2.0 5 votes vote down vote up
intl = useIntl();
Example #14
Source File: index.tsx    From ever-wallet-browser-extension with GNU General Public License v3.0 5 votes vote down vote up
export function AccountCard({ accountName, address, balance, publicKey }: Props): JSX.Element {
    const intl = useIntl()
    const wholePart = balance.split('.')?.[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    const decimals = balance.split('.')?.[1]

    return (
        <div className="account-card">
            <div className="account-card__info">
                <div className="account-card__info-details">
                    <div className="account-card__info-details-name">{accountName}</div>
                    <div className="account-card__info-details-public-key noselect">
                        {intl.formatMessage({ id: 'ACCOUNT_CARD_PUBLIC_KEY_LABEL' })}
                        <CopyText
                            className="account-card__info-details-public-key-value"
                            id={`copy-${publicKey}-${address}`}
                            place="top"
                            text={publicKey}
                        >
                            {convertPublicKey(publicKey)}
                        </CopyText>
                    </div>
                    <div className="account-card__info-details-public-key noselect">
                        {intl.formatMessage({ id: 'ACCOUNT_CARD_ADDRESS_LABEL' })}
                        {address !== undefined ? (
                            <CopyText
                                className="account-card__info-details-public-key-value"
                                id={`copy-${address}`}
                                place="top"
                                text={address}
                            >
                                {convertAddress(address)}
                            </CopyText>
                        ) : (
                            <span className="account-card__info-details-public-key-value">
                                {intl.formatMessage({ id: 'ACCOUNT_CARD_NO_ADDRESS_LABEL' })}
                            </span>
                        )}
                    </div>
                </div>
                <div className="account-card__info-balance">
                    {wholePart}
                    {`.${decimals || '00'} ${NATIVE_CURRENCY}`}
                </div>
            </div>

            <div className="account-card__pattern">
                <img src={Pattern} alt="" />
                {/*<div className="account-card__pattern-ellipsis">*/}
                {/*    <Ellipsis />*/}
                {/*</div>*/}
            </div>
        </div>
    )
}
Example #15
Source File: home.view.tsx    From malagu with MIT License 5 votes vote down vote up
export function Home() {
    const size = useContext(ResponsiveContext);
    const intl = useIntl();
    
    const loginUserManager = ContainerUtil.get<UserManager>(UserManager);
    const [user, setUser] = React.useState<User | undefined>(loginUserManager.userInfoSubject.value);
    React.useEffect(() => {
        const subscription = loginUserManager.userInfoSubject.subscribe(u => setUser(u));
        return () => subscription.unsubscribe();
    }, []);
    
    return (
    <StyledWraper style={size === 'small' ? { top: 0, bottom: 0, right: 0, left: 0 } : undefined }>
        <StyledContainer size={size}>
            <Box direction="column" pad="large" align="center" background="brand" round={ size === 'small' ? undefined : { corner: 'top', size: '4px' } }>
                <Button plain
                    href={ConfigUtil.get('accounts.home.url')}
                    icon={<Icon size="large" color="white" icon={ConfigUtil.get('accounts.logo.icon')}></Icon>}>
                </Button>
                <Heading level="4" color="white">{intl.formatMessage({ id: 'accounts.logo.label' })}</Heading>
            </Box>
            <Box direction="column" align="center" animation="slideDown" pad="large">
                {user && (
                    <Box direction="column" align="center">
                        <Avatar
                            hoverIndicator title={user.nickname} src={user.avatar} margin="small">
                        </Avatar>
                        <Text>{user.nickname}</Text>
                        <Text style={{ opacity: .7, fontSize: '.8em' }} >{user.email}</Text>
                        <Button
                            title={intl.formatMessage({ id: 'accounts.logout.label' })}
                            margin='small'
                            hoverIndicator
                            icon={<Logout/>}
                            onClick={() => loginUserManager.logout()}>
                        </Button>
                    </Box>
                )}
            </Box>
            <Box direction="column" fill="horizontal" style={ { position: 'absolute', bottom: 0 } } align="center">
                <LocaleMenu size="small" fontSize="12px"/>
            </Box>
        </StyledContainer>
    </StyledWraper>);

}
Example #16
Source File: Review.tsx    From project-loved-web with MIT License 5 votes vote down vote up
export default function Review({ review }: ReviewProps) {
  const intl = useIntl();

  const messageValues = {
    timestamp: dateFromString(review.reviewed_at),
    user: review.active_captain ? (
      <b>
        <UserInline user={review.captain} />{' '}
        <FormattedMessage
          defaultMessage='(captain)'
          description='[Reviews] Suffix on user for review listing'
        />
      </b>
    ) : (
      <>
        <UserInline user={review.captain} />
        {review.active_captain === false && (
          <>
            {' '}
            <FormattedMessage
              defaultMessage='(alumni)'
              description='[Reviews] Suffix on user for review listing'
            />
          </>
        )}
      </>
    ),
  };
  const scoreClass = reviewScoreClasses[review.score < -3 ? 0 : review.score + 3];

  return (
    <li>
      {review.score < -3 ? (
        <FormattedMessage
          defaultMessage='{user} marked as <score>not allowed</score> on {timestamp, date, long}'
          description='[Reviews] Review line for marking the map as not allowed'
          values={{
            ...messageValues,
            score: (c: ReactNode) => <span className={'review ' + scoreClass}>{c}</span>,
          }}
        />
      ) : (
        <FormattedMessage
          defaultMessage='{user} reviewed with {score} on {timestamp, date, long}'
          description='[Reviews] Review line'
          values={{
            ...messageValues,
            score: (
              <span className={'review ' + scoreClass}>
                {intl.formatMessage(reviewScoreMessages[review.score + 3])}
              </span>
            ),
          }}
        />
      )}
      {reviewIsNew(review) && (
        <span className='new'>
          {' ('}
          <FormattedMessage
            defaultMessage='New!'
            description='[Submissions] Indicator for content recently updated'
          />
          )
        </span>
      )}
      <div className={'submission-reason ' + scoreClass}>"{review.reason}"</div>
    </li>
  );
}
Example #17
Source File: AlertPage.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
export default function AlertPage() {
  const { formatMessage } = useIntl();

  return (
    <>
      <Title>{formatMessage({ defaultMessage: 'Alert 警告信息' })}</Title>
      <Description>
        {formatMessage({
          defaultMessage: '当某个页面需要向用户显示警告、提示的信息时使用,这部分信息是用户必须了解的。',
        })}
      </Description>
      <Subtitle>{formatMessage({ defaultMessage: '使用场景' })}</Subtitle>
      <Description>
        {formatMessage({ defaultMessage: '通常为页面级提示信息,提示重要性高,通常位置在页面或弹窗顶部。' })}
      </Description>
      <Subtitle>{formatMessage({ defaultMessage: '设计稿' })}</Subtitle>
      <Figma
        height="50%"
        collapsable
        url="https://www.figma.com/file/kP3A6S2fLUGVVMBgDuUx0f/GIO-Design?node-id=4093%3A45313"
      />

      <Heading>{formatMessage({ defaultMessage: '代码演示' })}</Heading>

      <Subheading>{formatMessage({ defaultMessage: '简单的警告提示' })}</Subheading>
      <Description>
        {formatMessage({ defaultMessage: '`Alert` 组件有四种不同程度的级别,每种都有自己独特的颜色。' })}
      </Description>
      <Canvas>
        <Story id="upgraded-alert--default" />
      </Canvas>

      <Subheading>{formatMessage({ defaultMessage: '描述信息' })}</Subheading>
      <Description>
        {formatMessage({ defaultMessage: '您可以使用 `description` 属性在标题下方显示描述信息。' })}
      </Description>
      <Canvas>
        <Story id="upgraded-alert--description" />
      </Canvas>

      <Subheading>{formatMessage({ defaultMessage: '图标' })}</Subheading>
      <Description>
        {formatMessage({
          defaultMessage: '您可以设置 `showIcon` 属性来显示默认的图标。您也可以设置 `icon` 属性,覆盖默认的图标。',
        })}
      </Description>
      <Canvas>
        <Story id="upgraded-alert--icons" />
      </Canvas>

      <Subheading>{formatMessage({ defaultMessage: '可关闭的' })}</Subheading>
      <Description>
        {formatMessage({
          defaultMessage:
            '您可以设置 `closeable` 属性,在 Alert 组件的右侧展示一个关闭按钮,点击后会隐藏 Alert 组件,同时触发 `onClose` 事件。',
        })}
      </Description>
      <Canvas>
        <Story id="upgraded-alert--closeable" />
      </Canvas>

      <Heading>{formatMessage({ defaultMessage: '参数说明' })}</Heading>
      <ArgsTable of={Alert} />
    </>
  );
}