react-intl#useIntl JavaScript 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: index.js    From ocp-advisor-frontend with Apache License 2.0 7 votes vote down vote up
Breadcrumbs = ({ current }) => {
  const intl = useIntl();
  const location = useLocation();
  const splitUrl = location.pathname.split('/');

  return (
    <div>
      <Breadcrumb ouiaId="detail">
        <BreadcrumbItem className="breadcrumb-item">
          <Link to={`/${splitUrl[1]}`}>
            {`${intl.formatMessage(messages.insightsHeader)} ${splitUrl[1]}`}
          </Link>
        </BreadcrumbItem>
        <BreadcrumbItem className="breadcrumb-item" isActive>
          {current}
        </BreadcrumbItem>
      </Breadcrumb>
    </div>
  );
}
Example #2
Source File: AppFooter.jsx    From koronawirus.lol with GNU Affero General Public License v3.0 6 votes vote down vote up
AppFooter = ({ }) => {
  const intl = useIntl()
  return (
    <>
      <Footer>
        <FooterText>
          <b><FormattedMessage id="footer1" /></b>&nbsp;
          <FormattedMessage id="footer2" values={{
            govLink: <a href={intl.formatMessage({id: "footerGovAddress"})}><FormattedMessage id="footer3" /></a>
          }} />
          <br />
          <FormattedMessage id="footer4" values={{
            star: <StarIcon />,
            githubLogo: <GithubIcon />,
            githubLink: <a href="https://github.com/808-Squad/koronawirus.lol"><FormattedMessage id="footer5" /></a>
          }} />
          <br />
          <FormattedMessage id="footer6" values={{
            freepik: <a href="https://www.freepik.com" title="Freepik">Freepik</a>,
            flaticon: <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a>
          }}/>
          <br />
          <FormattedMessage id="footer7" /> 14.12.2021
        </FooterText>
      </Footer>
    </>
  )
}
Example #3
Source File: index.js    From react-firebase-admin with MIT License 6 votes vote down vote up
useFormatMessage = (
  id,
  values = {},
  defaultMessage = '',
  description = ''
) => {
  const intl = useIntl();
  return intl.formatMessage({ id, defaultMessage, description }, values);
}
Example #4
Source File: CodeEditor.js    From malware-detection-frontend with Apache License 2.0 6 votes vote down vote up
CodeEditor = ({ code, language, isReadOnly, isDownloadEnabled, isCopyEnabled, height = '400px' }) => {
    const intl = useIntl();

    return <PfCodeEditor
        isDownloadEnabled={isDownloadEnabled}
        isCopyEnabled={isCopyEnabled}
        isReadOnly={isReadOnly}
        isLanguageLabelVisible={language}
        code={code}
        language={language}
        emptyState={
            <MessageState className='' icon={LockIcon} variant='small' title={intl.formatMessage(messages.sigCompiled)}
                text={intl.formatMessage(messages.sigCompiledBody)} />
        }
        height={height}
    />;
}
Example #5
Source File: index.js    From ocp-advisor-frontend with Apache License 2.0 6 votes vote down vote up
ClusterWrapper = () => {
  const intl = useIntl();
  const match = useRouteMatch();
  const cluster = useGetClusterByIdQuery({
    id: match.params.clusterId,
    includeDisabled: false,
  });

  useEffect(() => {
    cluster.refetch();
  }, [match.params.clusterId]);

  useEffect(() => {
    const subnav = `${
      cluster?.data?.report?.meta?.cluster_name || match.params.clusterId
    } - ${intl.formatMessage(messages.clusters)}`;
    insights.chrome.updateDocumentTitle(
      intl.formatMessage(messages.documentTitle, { subnav })
    );
  }, [cluster, match]);
  return <Cluster cluster={cluster} match={match} />;
}
Example #6
Source File: clone-badge.js    From strapi-molecules with MIT License 6 votes vote down vote up
CloneBadge = ({ isClone }) => {
  const { formatMessage } = useIntl();

  if (!isClone) {
    return '-';
  }

  return (
    <Wrapper>
      <Text lineHeight="19px">
        {formatMessage({
          id: 'preview.containers.List.clone',
        })}
      </Text>
    </Wrapper>
  );
}
Example #7
Source File: index.js    From strapi-plugin-config-sync with MIT License 6 votes vote down vote up
HeaderComponent = () => {
  const { formatMessage } = useIntl();

  return (
    <Box background="neutral100">
      <HeaderLayout
        title={formatMessage({ id: 'config-sync.Header.Title' })}
        subtitle={formatMessage({ id: 'config-sync.Header.Description' })}
        as="h2"
      />
    </Box>
  );
}
Example #8
Source File: index.js    From strapi-plugin-sitemap with MIT License 6 votes vote down vote up
SelectContentTypes = (props) => {
  const { formatMessage } = useIntl();

  const {
    contentTypes,
    onChange,
    disabled,
    value,
  } = props;

  return (
    <Select
      name="select"
      label={formatMessage({ id: 'sitemap.Settings.Field.SelectContentType.Label', defaultMessage: 'Content Type' })}
      hint={formatMessage({ id: 'sitemap.Settings.Field.SelectContentType.Description', defaultMessage: 'Select a content type.' })}
      disabled={disabled}
      onChange={(newValue) => onChange(newValue)}
      value={value}
    >
      {Object.entries(contentTypes).map(([uid, { displayName }]) => {
        return <Option value={uid} key={uid}>{displayName}</Option>;
      })}
    </Select>
  );
}
Example #9
Source File: CardOfVenue.js    From webpage with MIT License 6 votes vote down vote up
export default function SimpleCard() {
  const intl = useIntl()
  const classes = useStyles();
  const { venue } = settingsData()

  return (
    <Card className={classes.root} elevation={7}>
      <CardContent>
        <Typography className={classes.title} variant="subtitle1" gutterBottom>
          {intl.formatMessage({ defaultMessage:"Sede", description:"CardOfVenue: place" })}: {venue.name}
        </Typography>
        <Typography variant="body2">
          {intl.formatMessage({ defaultMessage:"El disol se realizara en las instalaciones del Instituto Tecnológico Superior de Cd. Serdán, Puebla. Se tendrá un ciclo de conferencias y talleres para los asistentes.", description:"CardOfVenue: description" })}
        </Typography>
      </CardContent>
      <CardActions>
        <Typography variant="caption">{venue.address}</Typography> 
        <MuiLink color="inherit" href={venue.location_url} target="_blank">
          <IconButton><DirectionsIcon /></IconButton>
        </MuiLink>
      </CardActions>
    </Card>
  );
}
Example #10
Source File: ToolbarButton.jsx    From volto-slate with MIT License 6 votes vote down vote up
ToolbarButton = React.forwardRef(
  ({ className, active, reversed, icon, style, title = '', ...props }, ref) => {
    const intl = useIntl();
    const i18ntitle =
      typeof title !== 'string' ? intl.formatMessage(title) : title;
    return (
      <div className="button-wrapper">
        <Button
          as="a"
          {...props}
          title={i18ntitle}
          ref={ref}
          style={style}
          className={cx(className)}
          active={active}
          inverted={reversed}
          compact
          toggle
          size="tiny"
          icon={icon && <Icon name={icon} size="24px" />}
        ></Button>
      </div>
    );
  },
)
Example #11
Source File: ChooseJobProfileSelect.js    From ui-data-export with Apache License 2.0 6 votes vote down vote up
ListSelect = ({ onChange }) => {
  const intl = useIntl();

  const options = [
    {
      value: '',
      label: '',
      disabled: true,
    },
    {
      value: 'instance',
      label: intl.formatMessage({ id: 'ui-data-export.instance' }),
    },
    {
      value: 'holding',
      label: intl.formatMessage({ id: 'ui-data-export.holdings' }),
    },
    {
      value: 'authority',
      label: intl.formatMessage({ id: 'ui-data-export.authorities' }),
    },
  ];

  return (
    <Row>
      <Col xs={6}>
        <Select
          data-testid="choose-job-select"
          required
          dataOptions={options}
          label={<FormattedMessage id="ui-data-export.jobProfiles.selectProfile.modal.selectTitle" />}
          defaultValue={options[0].value}
          onChange={onChange}
        />
      </Col>
    </Row>
  );
}
Example #12
Source File: index.js    From strapi-plugin-react-editorjs with MIT License 6 votes vote down vote up
Wysiwyg = ({
  name,
  className,
  error,
  description,
  intlLabel,
  required,
  onChange,
  style,
  value,
  disabled,
}) => {
  const { formatMessage } = useIntl();

  return (
    <Wrapper size={1} className={`${cn(!isEmpty(className) && className)}`} style={style}>            
      <Box>
        <Typography variant="pi" fontWeight="bold">
          {formatMessage(intlLabel)}
        </Typography>
        {required && (
          <Typography variant="pi" fontWeight="bold" textColor="danger600">
            *
          </Typography>
        )}
      </Box>
      <Editor onChange={onChange} value={value} name={name} disabled={disabled} />
      {error && (
        <Typography variant="pi" textColor="danger600">
          {formatMessage({ id: error, defaultMessage: error })}
        </Typography>
      )}
      {description && (
        <Typography variant="pi">{formatMessage(description)}</Typography>
      )}
      
    </Wrapper>
  )
}
Example #13
Source File: index.jsx    From elliot-serverless-ecommerce with MIT License 6 votes vote down vote up
Items = () => {
	const { locale, formatMessage } = useIntl();
	const { state } = useCart();

	const breadcrumbs = [
		{
			name: formatMessage({ id: "shop.page.title" }),
			link: `/[lang]/`,
			as: `/${locale}/`
		},
		{
			name: formatMessage({ id: "cart.page.title" }),
			link: `/[lang]/cart/`,
			as: `/${locale}/cart/`,
			active: true
		}
	];

	return (
		<>
			<PageTitle
				title={formatMessage({ id: "title.cart" })}
				breadcrumbs={breadcrumbs}
				breadCrumbsAlign="center"
			/>
			<ShoppingCart />
			{state?.data?.length > 0 && <Checkout />}
		</>
	);
}
Example #14
Source File: PathField.jsx    From tinkerun with MIT License 6 votes vote down vote up
PathField = () => {
  const intl = useIntl()
  const {errors, watch, setValue, register} = useFormContext()

  const isOverSSH = watch('is_over_ssh')

  return (
    <Pane
      display='flex'
    >
      <Field
        label={intl.formatMessage({id: 'connections.path'})}
        flex={1}
      >
        <TextInput
          height={majorScale(3)}
          placeholder='/var/www/html'
          width='100%'
          name='path'
          {...register('path')}
        />
      </Field>

      {!isOverSSH && (
        <Button
          height={majorScale(3)}
          marginLeft={16}
          flexShrink={0}
          onClick={() => setValue('path', selectDirectory())}
        >
          <FormattedMessage id='connections.select_directory'/>
        </Button>
      )}
    </Pane>
  )
}
Example #15
Source File: CountriesTable.js    From umami with MIT License 6 votes vote down vote up
export default function CountriesTable({ websiteId, onDataLoad, ...props }) {
  const { locale } = useLocale();
  const countryNames = useCountryNames(locale);
  const { formatMessage } = useIntl();

  function renderLink({ x: code }) {
    return (
      <div className={locale}>
        <FilterLink
          id="country"
          value={code}
          label={countryNames[code] ?? formatMessage(messages.unknown)}
        />
      </div>
    );
  }

  return (
    <MetricsTable
      {...props}
      title={formatMessage(messages.countries)}
      type="country"
      metric={formatMessage(messages.visitors)}
      websiteId={websiteId}
      onDataLoad={data => onDataLoad?.(percentFilter(data))}
      renderLabel={renderLink}
    />
  );
}
Example #16
Source File: index.js    From react-firebase-admin with MIT License 5 votes vote down vote up
useFormatDate = (value, options = {}) => {
  const intl = useIntl();
  return intl.formatDate(value, options);
}
Example #17
Source File: StatusCard.js    From malware-detection-frontend with Apache License 2.0 5 votes vote down vote up
StatusCard = ({ data: sigStatsData, loading: sigStatsLoading, noSigData }) => {
    const intl = useIntl();

    const EmptyAccountState = (
        <EmptyAccount message={intl.formatMessage(messages.emptyAccountCardBody)} />
    );

    const FilterResultState = (
        <GridItem span={!noSigData ? 6 : 12}>
            <MessageState className='' variant='large'
                icon={hasMalware() ? ExclamationCircleIcon : CheckCircleIcon}
                iconClass={hasMalware() ? 'ins-l-danger-color' : 'ins-l-success-color'}
                title={hasMalware() ?
                    intl.formatMessage(messages.activeFound) : intl.formatMessage(messages.noFound)}
                text={hasMalware() && intl.formatMessage(messages.hostsVulnerable)} >
                <span>{intl.formatMessage(messages.lastCheck)} </span>
                {sigStatsData?.hostScans?.nodes[0]
                    ? <DateFormat date={new Date(sigStatsData?.hostScans?.nodes[0].createdAt)} type='onlyDate' /> :
                    intl.formatMessage(messages.noAnalysisRun)}
            </MessageState>
        </GridItem>
    );

    return <Card className='ins-l-card'>
        <CardBody>
            <Grid>
                {sigStatsLoading ? <Loading /> : (sigStatsData.hosts?.totalCount === 0 && EmptyAccountState || FilterResultState)
                }
                {!noSigData && <React.Fragment>
                    <GridItem span={1}
                        className='pf-c-divider pf-m-vertical pf-m-inset-md pf-m-inset-none-on-md pf-m-inset-sm-on-lg pf-m-inset-xs-on-xl' />
                    {sigStatsLoading ? <Loading />
                        : <GridItem className='ins-l-sigStatCard' span={4}>
                            <GridItem className='ins-l-sigStat' span={12}>
                                <React.Fragment>
                                    <strong>{sigStatsData?.ruleStats?.matchedCount?.toLocaleString() || 0}</strong>
                                    <br />
                                    <Button className='ins-l-sigStatNum' variant='link'
                                        onClick={() => sigTableFilters({ ...sigTableFilters(), condition: { hasMatch: true } })}>
                                        <p>{intl.formatMessage(messages.matchedSignatures)}</p>
                                    </Button>
                                </React.Fragment>
                            </GridItem>
                            <GridItem className='ins-l-sigStat' span={12}>
                                <strong>{sigStatsData?.ruleStats?.enabledCount?.toLocaleString() || 0}</strong>
                                <p>{intl.formatMessage(messages.enabledSignatures)}</p></GridItem>
                            <GridItem className='ins-l-sigStat' span={12}>
                                <strong>{sigStatsData?.ruleStats?.disabledCount?.toLocaleString() || 0}</strong>
                                <p>{intl.formatMessage(messages.disabledSignatures)}</p></GridItem>
                        </GridItem>
                    }
                </React.Fragment>}
            </Grid>
        </CardBody>
    </Card >;
}
Example #18
Source File: App.js    From ocp-advisor-frontend with Apache License 2.0 5 votes vote down vote up
App = ({ useLogger, basename }) => {
  const intl = useIntl();
  const history = useHistory();
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const registry = getRegistry();
    registry.register({ notifications: notificationsReducer });
    insights.chrome.init();
    insights.chrome.auth.getUser().then(() => {
      setIsAuthenticated(true);
      setIsLoading(false);
    });
    insights.chrome.identifyApp('ocp-advisor');
    const unregister = insights.chrome.on('APP_NAVIGATION', (event) => {
      const targetUrl = event.domEvent?.href
        ?.replace(basename, '/')
        .replace(/^\/\//, '/');
      if (typeof targetUrl === 'string') {
        history.push(targetUrl);
      }
    });
    return () => unregister();
  }, []);
  return (
    <ErrorBoundary>
      {isLoading ? (
        <Bullseye>
          <Spinner />
        </Bullseye>
      ) : isAuthenticated ? (
        <Provider store={getStore(useLogger)}>
          <NotificationsPortal />
          <Routes />
        </Provider>
      ) : (
        <Bullseye>
          <MessageState
            variant="large"
            icon={LockIcon}
            title={intl.formatMessage(messages.permsTitle)}
            text={intl.formatMessage(messages.permsBody)}
          />
        </Bullseye>
      )}
    </ErrorBoundary>
  );
}
Example #19
Source File: index.js    From strapi-plugin-config-sync with MIT License 5 votes vote down vote up
ConfirmModal = ({ isOpen, onClose, onSubmit, type }) => {
  const { formatMessage } = useIntl();

  if (!isOpen) return null;

  return (
    <Dialog
      onClose={onClose}
      title="Confirmation"
      isOpen={isOpen}
    >
      <DialogBody icon={<ExclamationMarkCircle />}>
        <Stack size={2}>
          <Flex justifyContent="center">
            <Typography variant="omega" id="confirm-description" style={{ textAlign: 'center' }}>
              {formatMessage({ id: `config-sync.popUpWarning.warning.${type}_1` })}<br />
              {formatMessage({ id: `config-sync.popUpWarning.warning.${type}_2` })}
            </Typography>
          </Flex>
        </Stack>
      </DialogBody>
      <DialogFooter
        startAction={(
          <Button
            onClick={() => {
              onClose();
            }}
            variant="tertiary"
          >
            {formatMessage({ id: 'config-sync.popUpWarning.button.cancel' })}
          </Button>
        )}
        endAction={(
          <Button
            variant="secondary"
            onClick={() => {
              onClose();
              onSubmit();
            }}
          >
            {formatMessage({ id: `config-sync.popUpWarning.button.${type}` })}
          </Button>
        )} />
    </Dialog>
  );
}
Example #20
Source File: index.js    From strapi-plugin-sitemap with MIT License 5 votes vote down vote up
CMEditViewExclude = () => {
  const [sitemapSettings, setSitemapSettings] = useState({});
  const { formatMessage } = useIntl();
  const { slug, modifiedData, onChange } = useCMEditViewDataManager();

  const getSitemapSettings = async () => {
    const settings = await request('/sitemap/settings/', { method: 'GET' });
    setSitemapSettings(settings);
  };

  useEffect(async () => {
    getSitemapSettings();
  }, []);

  if (!sitemapSettings.contentTypes) return null;
  if (!sitemapSettings.contentTypes[slug]) return null;

  return (
    <Box paddingTop={6}>
      <Typography textColor="neutral600" variant="sigma">
        {formatMessage({ id: getTrad('plugin.name'), defaultMessage: 'Sitemap' })}
      </Typography>
      <Box paddingTop={2} paddingBottom={6}>
        <Divider />
      </Box>
      <Stack size={2}>
        <Box>
          <Checkbox
            onValueChange={(value) => {
              onChange({ target: { name: 'sitemap_exclude', value } });
            }}
            value={modifiedData.sitemap_exclude}
            name="exclude-from-sitemap"
          >
            {formatMessage({ id: getTrad('EditView.ExcludeFromSitemap'), defaultMessage: 'Exclude from sitemap' })}
          </Checkbox>
        </Box>
      </Stack>
    </Box>
  );
}
Example #21
Source File: LeftMenu.js    From webpage with MIT License 5 votes vote down vote up
function LeftMenu(props) {
  const intl = useIntl()
  const classes = useStyles();

  const sideList = () => (
    <div
      className={classes.list}
      role="presentation"
    >
      <AppBar position="static">
        <Toolbar>
          <Typography variant="h6" className={classes.title}>
            Menu
          </Typography>
        </Toolbar>
      </AppBar>    

      <List>
        <ListItem button component={Link} naked href="/" onClick={props.onClose}>
          <ListItemIcon>{<Icon>{"home"}</Icon>}</ListItemIcon>
          <ListItemText primary={<FormattedMessage defaultMessage="Inicio" description="leftMenu: title of inicio" />} />
        </ListItem>
        <ListItem button component={Link} naked href="/about" onClick={props.onClose}>
          <ListItemIcon>{<Icon>{"info"}</Icon>}</ListItemIcon>
          <ListItemText primary={<FormattedMessage defaultMessage="Quienes somos" description="leftMenu: title of about" />} />
        </ListItem>
        <ListItem button component={Link} naked href="/schedule" onClick={props.onClose}>
          <ListItemIcon>{<Icon>{"event"}</Icon>}</ListItemIcon>
          <ListItemText primary={<FormattedMessage defaultMessage="Programa" description="leftMenu: title of schedule" />} />
        </ListItem>
        {/**<ListItem button component={Link} naked href="/events" onClick={props.onClose}>
          <ListItemIcon>{<Icon>{"event"}</Icon>}</ListItemIcon>
          <ListItemText primary={<FormattedMessage defaultMessage="Eventos" description="leftMenu: title of events" />} />
        </ListItem>
        <ListItem button component={Link} naked href="/contact" onClick={props.onClose}>
          <ListItemIcon>{<Icon>{"contact_mail"}</Icon>}</ListItemIcon>
          <ListItemText primary={<FormattedMessage defaultMessage="Contacto" description="leftMenu: title of contact" />} />
        </ListItem>**/}
      </List>
      <Divider />
    </div>
  );

  return (
    <div>
      <SwipeableDrawer
        onClose={props.onClose}
        onOpen={() => {}}
        open={props.open}
      >
        {sideList()}
      </SwipeableDrawer>
    </div>
  );
}
Example #22
Source File: DetachedTextBlockEditor.jsx    From volto-slate with MIT License 5 votes vote down vote up
DetachedTextBlockEditor = (props) => {
  const {
    data,
    index,
    properties,
    onSelectBlock,
    onChangeBlock,
    block,
    selected,
    formTitle,
    formDescription,
  } = props;
  const { value } = data;

  const intl = useIntl();
  const placeholder =
    data.placeholder || formTitle || intl.formatMessage(messages.text);
  let instructions = data?.instructions?.data || data?.instructions;
  if (!instructions || instructions === '<p><br/></p>') {
    instructions = formDescription;
  }

  const { ref, inView } = useInView({
    threshold: 0,
    rootMargin: '0px 0px 200px 0px',
  });

  return (
    <div className="text-slate-editor-inner detached-slate-editor" ref={ref}>
      <SlateEditor
        index={index}
        readOnly={!inView}
        properties={properties}
        renderExtensions={[]}
        value={value}
        block={block /* is this needed? */}
        debug={DEBUG}
        onFocus={() => {
          if (!selected) {
            onSelectBlock(block);
          }
        }}
        onChange={(value, selection, editor) => {
          onChangeBlock(block, {
            ...data,
            value,
            plaintext: serializeNodesToText(value || []),
            // TODO: also add html serialized value
          });
        }}
        selected={selected}
        placeholder={placeholder}
        onKeyDown={handleKeyDetached}
      />
    </div>
  );
}
Example #23
Source File: generateAffectedRecordInfo.test.js    From ui-data-export with Apache License 2.0 5 votes vote down vote up
useGenerateAffectedRecordInfo = ({ logs }) => {
  const intl = useIntl();

  return { recordInfo: generateAffectedRecordInfo(logs, intl.formatMessage) };
}
Example #24
Source File: CreateRecordsWrapper.js    From ui-plugin-create-inventory-records with Apache License 2.0 5 votes vote down vote up
CreateRecordsWrapper = ({
  onClose,
  mutator: {
    createInstanceRecord,
    createHoldingsRecord,
    createItemRecord,
  },
}) => {
  const {
    identifierTypesByName,
    settings,
  } = useData();
  const callout = useCallout();
  const isLoading = useIsLoading();
  const intl = useIntl();

  const config = {
    ...initialValues,
    instance: {
      ...initialValues.instance,
      ...settings,
    },
  };

  const handleSubmit = useCallback(async (formData) => {
    const {
      instance,
      holding,
      item,
    } = formData;

    try {
      const instanceRecord = await createInstanceRecord.POST(parseInstance(instance, identifierTypesByName));
      const holdingsRecord = await createHoldingsRecord.POST(parseHolding(holding, instanceRecord));
      const itemRecord = await createItemRecord.POST(parseItem(item, holdingsRecord));

      callout.sendCallout({
        message: <FormattedMessage id="ui-plugin-create-inventory-records.onSave.success" />,
      });

      onClose({
        instanceRecord,
        holdingsRecord,
        itemRecord,
      });
    } catch (error) {
      callout.sendCallout({
        message: <FormattedMessage id="ui-plugin-create-inventory-records.onSave.error" />,
        type: 'error',
      });
    }
  }, [
    onClose,
    callout,
    createInstanceRecord,
    createHoldingsRecord,
    createItemRecord,
    identifierTypesByName,
  ]);

  if (isLoading) return null;

  return (
    <Paneset>
      <Layer
        isOpen
        inRootSet
        contentLabel={intl.formatMessage({ id: 'ui-plugin-create-inventory-records.fastAddLabel' })}
      >
        <CreateRecordsForm
          onSubmit={handleSubmit}
          onClose={onClose}
          initialValues={config}
        />
      </Layer>
    </Paneset>
  );
}
Example #25
Source File: index.js    From rainbow-modules with MIT License 5 votes vote down vote up
export default function EmailPasswordSignInForm(props) {
    const { className, style } = props;
    const intl = useIntl();
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const app = useFirebaseApp();

    const emailPlaceholder = intl.formatMessage(messages.emailPlaceholder);
    const passwordPlaceholder = intl.formatMessage(messages.passwordPlaceholder);

    const handleSubmit = async (event) => {
        event.preventDefault();
        try {
            showAppSpinner();
            await app.auth().signInWithEmailAndPassword(email, password);
            hideAppSpinner();
        } catch (error) {
            hideAppSpinner();
            showAppMessage({
                message: `${error}`,
                variant: 'error',
            });
        }
    };

    return (
        <form className={className} style={style} onSubmit={handleSubmit} noValidate>
            <StyledInput
                required
                label={emailLabel}
                placeholder={emailPlaceholder}
                type="email"
                name="email"
                icon={emailIcon}
                value={email}
                onChange={({ target: { value } }) => setEmail(value)}
            />
            <StyledInput
                required
                label={passwordLabel}
                placeholder={passwordPlaceholder}
                type="password"
                name="password"
                icon={passwordIcon}
                value={password}
                onChange={({ target: { value } }) => setPassword(value)}
            />
            <StyledButton type="submit" variant="brand" label={buttonLabel} />
        </form>
    );
}