@material-ui/core#Button TypeScript Examples

The following examples show how to use @material-ui/core#Button. 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: register.tsx    From 0Auth with MIT License 7 votes vote down vote up
function Register({ submit }: UserProps) {
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [age, setAge] = useState('');
  const [address, setAddress] = useState('');
  const submitInfo = () => submit(name, phone, age, address);

  return (
    <div className="User">
      <h2>Register Info</h2>
      <form noValidate>
        <TextField required id="name" value={name} onChange={e => setName(e.target.value)} label="Name"/><br/>
        <TextField required id="phone" value={phone} onChange={e => setPhone(e.target.value)} label="Phone"/><br/>
        <TextField required id="age" value={age} onChange={e => setAge(e.target.value)} label="Age"/><br/>
        <TextField required id="address" value={address} onChange={e => setAddress(e.target.value)} label="Address"/><br/><br/>
        <Button variant="contained" color="primary" onClick={submitInfo}>
          Submit
        </Button>
      </form>
    </div>
  );
}
Example #2
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 #3
Source File: movie.tsx    From 0Auth with MIT License 6 votes vote down vote up
function Movie({ id, name, age_limit, ticket, bookMovie }: MovieProps) {
  const classes = useStyles();

  return (
    <Card className={classes.root} variant="outlined">
      <CardContent>
        <Typography className={classes.title} color="textSecondary" gutterBottom>
          {name}
        </Typography>
        <Typography className={classes.pos} color="textSecondary">
          age limit: {age_limit}
        </Typography>
      </CardContent>
      {
        ticket !== undefined
          ? (
            <CardActions>
              <Button size="small">Already Book</Button>
            </CardActions>
          )
          : (
            <CardActions onClick={() => bookMovie(id)}>
              <Button size="small">Reservation</Button>
            </CardActions>
          )
      }
    </Card>
  );
}
Example #4
Source File: Dialog.tsx    From Demae with MIT License 6 votes vote down vote up
_Dialog = ({ open, title, body, actions, onClose }: { open: boolean, title?: string, body?: string, actions: Action[], onClose: () => void }) => {
	if (open) {
		return (
			<Dialog onClose={onClose} open={open} maxWidth='md'>
				<div style={{ minWidth: '280px' }}>
					<DialogTitle>
						{title}
					</DialogTitle>
					{body && <DialogContent dividers>
						{body}
					</DialogContent>}
					<DialogActions>
						{actions.map((action, index) => {
							return (
								<Button key={index} variant={action.variant} color={action.color} autoFocus={action.autoFocus} onClick={() => {
									onClose()
									if (action.handler) {
										action.handler()
									}
								}}>
									{action.title}
								</Button>
							)
						})
						}
					</DialogActions>
				</div>
			</Dialog>
		)
	}
	return <></>
}
Example #5
Source File: AppBar.tsx    From firetable with Apache License 2.0 6 votes vote down vote up
AppBar: React.FunctionComponent<IAppBarProps> = () => {
  const classes = useStyles();
  const theme = useTheme();
  const trigger = useScrollTrigger({ disableHysteresis: true, threshold: 0 });

  return (
    <MuiAppBar
      position="sticky"
      color="default"
      className={classes.appBar}
      elevation={trigger ? 4 : 0}
    >
      <Toolbar>
        <Grid item xs>
          <FiretableLogo />
        </Grid>

        <Grid item>
          <Button
            component={Link}
            to={routes.signOut}
            color="primary"
            variant="outlined"
          >
            Sign Out
          </Button>
        </Grid>
      </Toolbar>
    </MuiAppBar>
  );
}
Example #6
Source File: inPageNav.tsx    From mano-aloe with MIT License 6 votes vote down vote up
export default function InPageNav() {
    const classes = useStyles();

    return (
        <div className="in-page-nav">
            <NavLink to={"/game"}>
                <Button variant="contained" startIcon={<SportsEsportsIcon />} size="large" color="primary" className={classes.containedPrimary}>
                    Games
                </Button>
            </NavLink>
            <NavLink to={"/art"}>
                <Button variant="contained" startIcon={<PhotoLibraryIcon />} size="large" color="primary" className={classes.containedPrimary}>
                    Gallery
                </Button>
            </NavLink>
        </div>
    );
}
Example #7
Source File: RenderErrorView.tsx    From abacus with GNU General Public License v2.0 6 votes vote down vote up
export default function (props: { renderError: RenderError }): JSX.Element {
  const classes = useStyles()
  return (
    <div className={classes.root}>
      <Dialog open={true} maxWidth={false}>
        <DialogTitle disableTypography>
          <Typography variant='h5'>Oops! Something went wrong...</Typography>
        </DialogTitle>
        <DialogContent className={classes.dialogContent}>
          <img
            src='/img/hippo-with-turtle.jpg'
            alt={`"hippo" by .wilkie is licensed with CC BY-NC-SA 2.0. To view a copy of this license, visit https://creativecommons.org/licenses/by-nc-sa/2.0/`}
          />
          <pre className={classes.pre}>{props.renderError.error.stack || props.renderError.error.message}</pre>
        </DialogContent>
        <DialogActions>
          <Button component={'a'} href='/'>
            Go home
          </Button>
          <Button onClick={props.renderError.clear} color='primary'>
            Try again
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  )
}
Example #8
Source File: LandingPage.tsx    From firebase-react-typescript-project-template with MIT License 6 votes vote down vote up
LandingPage = () => {
  const logout = useLogout();
  return (
    <>
      <Typography variant="h3">You&#39;re authed!</Typography>
      <Button variant="contained" size="large" color="primary" onClick={logout}>
        Log out
      </Button>
    </>
  );
}
Example #9
Source File: Confirmation.tsx    From clarity with Apache License 2.0 6 votes vote down vote up
render() {
    return (
      <Dialog
        open={this.props.show}
        onClose={this.props.dismiss}
        aria-labelledby="alert-dialog-title"
        aria-describedby="alert-dialog-description"
      >
        <DialogTitle id="alert-dialog-title">{this.props.title}</DialogTitle>
        <DialogContent>
          <DialogContentText id="alert-dialog-description">
            {this.props.confirmation}
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button
            onClick={() => {
              this.props.cancel();
            }}
            color="secondary"
          >
            {this.props.cancelLabel}
          </Button>
          <Button
            onClick={() => {
              this.props.proceed();
            }}
            color="primary"
            autoFocus
          >
            {this.props.proceedLabel}
          </Button>
        </DialogActions>
      </Dialog>
    );
  }
Example #10
Source File: OverclockingCard.tsx    From Pi-Tool with GNU General Public License v3.0 6 votes vote down vote up
EnableOverclockingDialog: React.FC<EnableOverclockingDialogProps> = ({ onClose, open }) => {
    const classes = useStyles();

    const handleCancel = () => { onClose(false) }
    const handleOk = () => { onClose(true) }

    return (
        <Dialog
            disableBackdropClick
            disableEscapeKeyDown
            maxWidth="xs"
            aria-labelledby="confirmation-dialog-title"
            open={open}>
            <DialogTitle id="confirmation-dialog-title">
                <Typography variant="h5" className={classes.iconHeader}>
                    <WarningIcon />  Overclocking warning
	      </Typography>
            </DialogTitle>
            <DialogContent>
                <Typography>
                    It is recommended that you save any important data before using this tool. Operating your Raspberry Pi outside of official Raspberry Pi specifications or outside factory settings, including the conducting of overclocking, may damage your system components and lead to system instabilities. <br /> <br /> Cooler Master does not provide support or service for issues or damages related to use of the system components outside of official specifications or factory settings. You may also not receive support from your board or system manufacturer.
		</Typography>
            </DialogContent>
            <DialogActions>
                <Button autoFocus onClick={handleCancel} color="primary" variant="contained">
                    Cancel
	    </Button>
                <Button onClick={handleOk} color="primary" variant="contained">
                    Ok
	    </Button>
            </DialogActions>
        </Dialog>
    )
}
Example #11
Source File: ChallengeCard.tsx    From DamnVulnerableCryptoApp with MIT License 6 votes vote down vote up
ChallengeCard = (props: IChallengeCardProps) => {

  const history = useHistory();
  const done = <Chip size="small" label="Done" style={{ backgroundColor: 'green', color: 'white' }} />;

  const onChallengeClick = (path: string) => {
    return () => {
      history.push(path);
    };
  };


  return (
    <Card>
      <CardActionArea>
        <CardContent style={{ height: '180px' }} onClick={onChallengeClick(props.challenge.url)}>
          <Typography gutterBottom variant="h5" component="h2" style={{ height: '60px' }}>
            {pad(props.index + 1, 2)} - {props.challenge.name}
          </Typography>
          <Typography variant="body2" color="textSecondary" component="p">
            {props.challenge.description}
          </Typography>
        </CardContent>
      </CardActionArea>
      <CardActions>
        <Button size="small" color="primary" onClick={onChallengeClick(props.challenge.url)}>
          Take the challenge
        </Button>
        {props.done ? done : ""}
      </CardActions>
    </Card >
  );

}
Example #12
Source File: BubbleChart.tsx    From react-tutorials with MIT License 6 votes vote down vote up
render() {
    return (
      <div>
        <Button
          className="buttonFixed"
          variant="contained"
          color="default"
          onClick={() => {
            this.animateBubbles()
          }}
        >
          Animate
        </Button>

        <div aria-hidden="true" id="chart" style={{ background: this.props.backgroundColor, cursor: 'pointer' }}>
          <svg width={this.props.width} height={this.props.height}>
            {this.renderBubbles(this.state.data as [])}
          </svg>
        </div>
      </div>
    )
  }
Example #13
Source File: send_button.tsx    From jupyter-extensions with Apache License 2.0 6 votes vote down vote up
export function SendButton(props) {
  return (
    <Button
      type="submit"
      color="primary"
      size="small"
      endIcon={<Icon>send</Icon>}
      className={props.type}
    >
      Send
    </Button>
  );
}
Example #14
Source File: GameEnded.tsx    From cards-against-formality-pwa with BSD 2-Clause "Simplified" License 6 votes vote down vote up
export default function GameEnded({ game, players }: { game: any, players: any }) {
  const { user } = useContext(UserContext);
  const winners = useMemo(() => {
    return game.winner.map((winner: string) => players.find((player: any) => player._id === winner));
  }, [game, players]);

  useEffect(() => {
    (window as any)?.gtag('event', 'game_ended');
  }, []);

  return <div className="game-ended-container">
    <Typography variant="h3" className="game-ended-header">
      Game over!
    </Typography>
    <div className="winners-container">
      {winners?.length ? winners.map(({ username, score }: any) => {
        return <Typography variant="h4" key={username}>
          {username === user?.username ? "You win!" : `${username} wins!`} with {score} points
      </Typography>
      }) : null}
    </div>
    <div className="content-wrapper">
      <Typography variant="body1">
        If you enjoyed the game and would like to help keep the servers alive, please consider buying me a coffee.
      </Typography>
      <Button onClick={() => window.open("https://www.buymeacoffee.com/cards")} color="primary" variant="contained">Buy me a coffee</Button>
    </div>
  </div>
}
Example #15
Source File: BootstrapButton.tsx    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
BootstrapButton = withStyles({
  root: {
    boxShadow: 'none',
    textTransform: 'none',
    fontSize: 16,
    padding: '6px 12px',
    border: '1px solid',
    lineHeight: 1.5,
    color: '#ffffff',
    backgroundColor: '#4138ff',
    borderColor: '#4138ff',
    fontFamily: [
      '-apple-system',
      'BlinkMacSystemFont',
      '"Segoe UI"',
      'Roboto',
      '"Helvetica Neue"',
      'Arial',
      'sans-serif',
      '"Apple Color Emoji"',
      '"Segoe UI Emoji"',
      '"Segoe UI Symbol"',
    ].join(','),
    '&:hover': {
      backgroundColor: '#4138dd',
      borderColor: '#4138dd',
      boxShadow: 'none',
    },
    '&:active': {
      boxShadow: 'none',
      backgroundColor: '#4138ee',
      borderColor: '#4138ee',
    },
    '&:focus': {
      boxShadow: '0 0 0 0.2rem rgba(0,123,255,.5)',
    },
  },
})(Button)
Example #16
Source File: Main.tsx    From SpaceEye with MIT License 6 votes vote down vote up
WindowsOnboardingDialog: React.FC<WindowsOnboardingDialogProps> = props => (
    <Dialog open={props.show} style={{ userSelect: 'none' }}>
        <DialogTitle>Welcome to SpaceEye!</DialogTitle>
        <DialogContent>
            <DialogContentText>
                To make sure the app icon is always visible in your taskbar, click the button below
                and select &quot;Show icon and notifications&quot; for &quot;SpaceEye&quot;.
            </DialogContentText>
            <DialogContentText>
                You can do this later by Windows searching for &quot;Select which icons appear on
                the taskbar&quot;
            </DialogContentText>
        </DialogContent>
        <DialogActions>
            <Button onClick={props.onDone}>Done</Button>
            <Button color="primary" onClick={props.onOpenSettings}>
                Open Icon Settings
            </Button>
        </DialogActions>
    </Dialog>
)
Example #17
Source File: hotel-edit.component.tsx    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
HotelEditComponent: React.FunctionComponent<Props> = (props) => {
  const { hotel, cities, onSave } = props;

  return (
    <Formik
      onSubmit={onSave}
      initialValues={hotel}
      enableReinitialize={true}
      validate={formValidation.validateForm}
    >
      {() => (
        <Form className={classes.root}>
          <TextFieldComponent name="name" label="Name" />
          <TextFieldComponent name="address" label="Address" />
          <img className={classes.picture} src={hotel.picture} />
          <RatingComponent name="rating" max={5} />
          <SelectComponent name="city" label="City" items={cities} />
          <TextFieldComponent
            name="description"
            label="Description"
            multiline={true}
            rows={3}
            rowsMax={5}
          />
          <Button type="submit" variant="contained" color="primary">
            Save
          </Button>
        </Form>
      )}
    </Formik>
  );
}
Example #18
Source File: BankAccountItem.tsx    From End-to-End-Web-Testing-with-Cypress with MIT License 6 votes vote down vote up
BankAccountListItem: React.FC<BankAccountListItemProps> = ({
  bankAccount,
  deleteBankAccount,
}) => {
  return (
    <ListItem data-test={`bankaccount-list-item-${bankAccount.id}`}>
      <Grid container direction="row" justify="space-between" alignItems="flex-start">
        <Grid item>
          <Typography variant="body1" color="primary" gutterBottom>
            {bankAccount.bankName} {bankAccount.isDeleted ? "(Deleted)" : undefined}
          </Typography>
        </Grid>
        {!bankAccount.isDeleted && (
          <Grid item>
            <Button
              variant="contained"
              color="secondary"
              size="large"
              data-test="bankaccount-delete"
              onClick={() => {
                deleteBankAccount({ id: bankAccount.id });
              }}
            >
              Delete
            </Button>
          </Grid>
        )}
      </Grid>
    </ListItem>
  );
}
Example #19
Source File: LiveStreamFooter.tsx    From twitch-live-extension with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
LiveStreamFooter = () => {
    const classes = useStyles();
    const dispatch: AppDispatch = useDispatch();

    const { loading } = useSelector((state: RootState) => state.common);

    return (
        <div className={classes.root}>
            {!loading && (
                <Button
                    className={classes.button}
                    variant="outlined"
                    color="default"
                    size={'small'}
                    disabled={loading}
                    startIcon={<SyncIcon />}
                    onClick={() => dispatch(getLiveStreams())}
                >
                    Refresh
                </Button>
            )}

            <Button
                component={Link}
                className={classes.button}
                variant="outlined"
                size={'small'}
                disabled={loading}
                startIcon={<SettingsIcon />}
                to="/settings"
            >
                Settings
            </Button>
        </div>
    );
}
Example #20
Source File: TransactionConfirmationModal.tsx    From interface-v2 with GNU General Public License v3.0 6 votes vote down vote up
TransactionErrorContent: React.FC<TransactionErrorContentProps> = ({
  message,
  onDismiss,
}) => {
  const classes = useStyles();
  return (
    <Box padding={4}>
      <Box>
        <Box className={classes.modalHeader}>
          <Typography variant='h5' color='error'>
            Error!
          </Typography>
          <CloseIcon onClick={onDismiss} />
        </Box>
        <Box className={classes.modalContent}>
          <TransactionFailed />
          <Typography variant='body1'>{message}</Typography>
        </Box>
      </Box>
      <Button className={classes.submitButton} onClick={onDismiss}>
        Dismiss
      </Button>
    </Box>
  );
}
Example #21
Source File: ModsToolbar.tsx    From ow-mod-manager with MIT License 6 votes vote down vote up
ModsToolbar: React.FunctionComponent = () => {
  const styles = useStyles();
  const inAlphaMode = useRecoilValue(settingsState).alphaMode;
  const [filter, setFilter] = useRecoilState(modFilterState);
  const { owmlPath, alphaPath } = useRecoilValue(settingsState);
  return (
    <Paper>
      <Toolbar className={styles.toolBar}>
        <FilterInput
          value={filter}
          onChange={setFilter}
          label={modsText.toolbar.findModsLabel}
        />
        <Button
          startIcon={<FolderIcon />}
          onClick={() =>
            openDirectory(
              inAlphaMode ? `${alphaPath}/BepInEx/plugins` : `${owmlPath}/Mods`
            )
          }
          variant="outlined"
        >
          {modsText.toolbar.modsDirectory}
        </Button>
      </Toolbar>
    </Paper>
  );
}
Example #22
Source File: ControlsCategoryButton.tsx    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
_ControlsCategoryButton: FunctionComponent<ControlsCategoryButtonProps> = ({
  active,
  style,
  nameKey,
  displayed,
  enableCategory,
}) => {
  const classes = useStyles();

  if (!displayed) {
    return null;
  }

  const buttonStyle = {
    backgroundColor: active ? style.enabled.bg : style.disabled.bg ?? '#FFF',
    color: active ? style.enabled.text : style.disabled.text ?? '#000',
    flexBasis: style.fullWidth ? '95%' : 'auto',

    // Moved down here from makeStyles because styles were breaking.
    margin: '4px 4px 4px 4px',
    padding: '8px 4px 8px 4px',
    flex: '1 0 25%',
  };

  return (
    <Button
      onClick={enableCategory}
      variant="contained"
      style={buttonStyle}
      className={classes.categoryButton}
    >
      {t(nameKey)}
    </Button>
  );
}
Example #23
Source File: Detail.tsx    From Demae with MIT License 5 votes vote down vote up
CommentView = ({ order }: { order: Order }) => {
	const [auth] = useAuthUser()
	const theme = useTheme();
	const [user] = useDocumentListen<Social.User>(Social.User, auth ? Social.User.collectionReference().doc(auth!.uid) : undefined)
	const [textField, setValue] = useTextField()

	const onSubmit = async (event) => {
		event.preventDefault();
		if (!auth) return
		const comment = new Comment()
		comment.text = textField.value as string
		const activity = new Activity(order.activities.collectionReference.doc())
		activity.authoredBy = auth.uid
		activity.comment = comment
		try {
			await activity.save()
			setValue("")
		} catch (error) {
			console.error(error)
		}
	}

	return (
		<form onSubmit={onSubmit}>
			<Box display="flex" paddingY={3}>
				<Box>
					<Avatar variant="circle">
						<ImageIcon />
					</Avatar>
				</Box>
				<Box
					flexGrow={1}
					border={1}
					borderColor={theme.palette.grey[300]}
					borderRadius={8}
					marginLeft={2}
				>
					<Box display="flex"
						style={{
							background: theme.palette.grey[100]
						}}
					>
						<Box display="flex" padding={2} paddingY={1}>
							<Typography>{user?.name || "YOU"}</Typography>
						</Box>
					</Box>
					<Box
						padding={1}
					>
						<TextField
							{...textField}
							fullWidth multiline
							size="small"
							variant="outlined"
							placeholder="comment"
							rows={4}
						/>
						<Box
							display="flex"
							justifyContent="flex-end"
							paddingTop={2}
						>
							<Button
								type="submit"
								disabled={((textField.value as string)?.length == 0)}
								size="small"
								color="primary"
								variant="contained"
								disableElevation
							>Comment</Button>
						</Box>
					</Box>
				</Box>
			</Box>
		</form>
	)
}
Example #24
Source File: BetaBanner.tsx    From akashlytics with GNU General Public License v3.0 5 votes vote down vote up
BetaBanner = () => {
  const [isBetaBarVisible, setIsBetaBarVisible] = useState(false);
  const classes = useStyles();

  useEffect(() => {
    const isBetaBarSeen = localStorage.getItem("isBetaBarSeen");
    setIsBetaBarVisible(isBetaBarSeen === null ? true : false);
  }, []);

  const hideIsBetaBarVisible = () => {
    localStorage.setItem("isBetaBarSeen", "true");
    setIsBetaBarVisible(false);
  };

  return (
    <>
      {isBetaBarVisible && (
        <AppBar position="static" color="default" className={classes.root}>
          <Toolbar>
            <Chip label="BETA" color="primary" className={classes.betaChip} />
            <div className={classes.betaText}>
              <Box marginBottom=".5rem">
                <Typography variant="body2">
                  Akashlytics Deploy is now currently in open BETA.
                </Typography>
              </Box>
              <Button
                component={Link}
                to="/deploy"
                variant="contained"
                size="small"
                onClick={() => hideIsBetaBarVisible()}
              >
                Take a look!
              </Button>
            </div>

            <div className={classes.grow} />
            <IconButton
              aria-label="Close beta app bar"
              color="inherit"
              onClick={() => hideIsBetaBarVisible()}
            >
              <CloseIcon />
            </IconButton>
          </Toolbar>
        </AppBar>
      )}
    </>
  );
}
Example #25
Source File: index.tsx    From firetable with Apache License 2.0 5 votes vote down vote up
/* TODO implement parameter "tags" that defines available tags and values
{
    row: "You have access to the object 'row' at...",
    ref: "...",
    ...: ...
}
*/
export default function CodeEditorHelper({ docLink }) {
  const { tableState } = useFiretableContext();
  const availableVariables = [
    {
      key: "row",
      description: `row has the value of doc.data() it has type definitions using this table's schema, but you can access any field in the document.`,
    },
    {
      key: "db",
      description: `db object provides access to firestore database instance of this project. giving you access to any collection or document in this firestore instance`,
    },
    {
      key: "ref",
      description: `ref object that represents the reference to the current row in firestore db (ie: doc.ref).`,
    },
    {
      key: "auth",
      description: `auth provides access to a firebase auth instance, can be used to manage auth users or generate tokens.`,
    },
    {
      key: "storage",
      description: `firebase Storage can be accessed through this, storage.bucket() returns default storage bucket of the firebase project.`,
    },
    {
      key: "utilFns",
      description: `utilFns provides a set of functions that are commonly used, such as easy access to GCP Secret Manager`,
    },
  ];
  return (
    <Box marginBottom={1} display="flex" justifyContent="space-between">
      <Box>
        You have access to:{" "}
        {availableVariables.map((v) => (
          <AvailableValueTag label={v.key} details={v.description} />
        ))}
      </Box>
      <Button
        size="small"
        endIcon={<OpenIcon />}
        target="_blank"
        href={docLink}
      >
        Examples & Docs
      </Button>
    </Box>
  );
}
Example #26
Source File: VerifyEmailAction.tsx    From firebase-react-typescript-project-template with MIT License 5 votes vote down vote up
VerifyEmailAction = ({ actionCode }: Props) => {
  const classes = useStyles({});

  const [validCode, setValidCode] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const applyActionCode = async () => {
      try {
        await firebase.auth().applyActionCode(actionCode);
        // Email address has been verified.
        setValidCode(true);
      } catch (err) {
        // Code is invalid or expired. Ask the user to verify their email address again
        setValidCode(false);
      } finally {
        setLoading(false);
      }
    };
    applyActionCode();
  }, [actionCode]);

  if (loading) {
    return <LoadingDiv />;
  }

  if (validCode) {
    return (
      <>
        <div>
          <CheckMark />
        </div>
        <Typography variant="h6" align="center">
          Your email has been verified.
        </Typography>

        <Typography variant="body1" align="center" gutterBottom>
          You can now sign in with your new account.
        </Typography>
        <Link to={SIGNIN_ROUTE} className={classes.link}>
          <Button type="submit" variant="contained" color="primary">
            Sign in
          </Button>
        </Link>
      </>
    );
  }

  return (
    <>
      <Typography variant="h4" align="center" className={classes.errorText}>
        Error
      </Typography>
      <Typography
        variant="subtitle1"
        align="center"
        className={classes.errorText}
      >
        Your email has already been verified, or the verification code has
        expired. <br /> Try verifying email again by resending a verification
        code, or trying to log in.
      </Typography>
    </>
  );
}
Example #27
Source File: AccountPage.tsx    From clarity with Apache License 2.0 5 votes vote down vote up
renderImportForm() {
    const form = this.accountForm as ImportAccountFormData;
    return (
      <form className={this.props.classes.root}>
        <FormControl>
          <Typography id="continuous-slider" gutterBottom>
            Private Key File
          </Typography>
          <Box
            display={'flex'}
            flexDirection={'row'}
            alignItems={'center'}
            m={1}
          >
            <Button
              id={'private-key-uploader'}
              variant="contained"
              color="primary"
              component="label"
            >
              Upload
              <input
                type="file"
                style={{ display: 'none' }}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                  form.handleFileSelect(e)
                }
              />
            </Button>
            <Box ml={1}>
              <Typography>
                <Box fontSize={12}>
                  {form.file ? form.file.name : 'No file selected'}
                </Box>
              </Typography>
            </Box>
          </Box>
        </FormControl>
        <TextFieldWithFormState
          fullWidth
          label="Name"
          placeholder="Human Readable Alias"
          id="import-name"
          fieldState={this.accountForm.name}
        />
        <FormControl fullWidth className={this.props.classes.importButton}>
          <Button
            disabled={this.accountForm.submitDisabled}
            color="primary"
            variant={'contained'}
            onClick={() => {
              this.onImportAccount();
            }}
          >
            Import
          </Button>
        </FormControl>
      </form>
    );
  }
Example #28
Source File: MetaMaskConnector.tsx    From metamask-snap-polkadot with Apache License 2.0 5 votes vote down vote up
MetaMaskConnector = () => {

    const [state, dispatch] = useContext(MetaMaskContext);

    useEffect( () => {
        (async () => {
            if(await isPolkadotSnapInstalled()) {
                dispatch({type: MetamaskActions.SET_INSTALLED_STATUS, payload: {isInstalled: true}});
            }
        })();
    }, [dispatch]);

    const installSnap = useCallback(async () => {
       const isInitiated = await installPolkadotSnap();
       if(!isInitiated) {
           dispatch({type: MetamaskActions.SET_INSTALLED_STATUS, payload: {isInstalled: false, message: "Please accept snap installation prompt"}})
       } else {
           dispatch({type: MetamaskActions.SET_INSTALLED_STATUS, payload: {isInstalled: true}});
       }
    }, [dispatch]);

    const handleClose = (event: React.SyntheticEvent | React.MouseEvent, reason?: string) => {
        if (reason === 'clickaway') {
          return;
        }
        dispatch({type: MetamaskActions.SET_INSTALLED_STATUS, payload: false})
      };
    
    const shouldDisplaySnackbar = (): boolean => {
      if (!state.polkadotSnap.isInstalled && state.polkadotSnap.message) return true;
      else return false;
    }

    return(
        <div>
            <Snackbar
                anchorOrigin={{
                    vertical: 'bottom',
                    horizontal: 'left',
                }}
                open={shouldDisplaySnackbar()}
                autoHideDuration={6000}
                onClose={handleClose}
                message={state.polkadotSnap.message}
                action={
                    <React.Fragment>
                      <IconButton size="small" aria-label="close" color="inherit" onClick={handleClose}>
                        <CloseIcon fontSize="small" />
                      </IconButton>
                    </React.Fragment>
                  }
            />
            <Hidden xsUp={state.hasMetaMask}>
                <Alert severity="warning">Ensure that MetaMask is installed!</Alert>
                <Box mt={"1rem"} />
            </Hidden>
            <Button
                disabled={!state.hasMetaMask}
                onClick={installSnap}
                variant="contained"
                size={"large"}
                color="primary"
            >
                Connect to MetaMask
            </Button>
        </div>
    );

}
Example #29
Source File: KeyModal.tsx    From DamnVulnerableCryptoApp with MIT License 5 votes vote down vote up
KeyModal = (props: IModalProps) => {

  const layoutContext = useContext(LayoutContext);
  const classes = useStyles();

  const onLoginClicked = () => {
    layoutContext.setLoading(true);

    KeyDisclosureService.unlockMailbox(props.mailboxKey).then(res => {
      layoutContext.setLoading(false);
      if (res.success) {
        props.setFlag(res.flag);
        props.setInboxUnlocked(true);
        props.setEmails(res.emails);
        props.setSelectedEmail(res.emails[0]);
      }
    }).catch(() => layoutContext.setLoading(false));
  };

  const onMailboxChange = (e: React.ChangeEvent<HTMLInputElement>) => props.setMailboxKey(e.target.value);
  const getContainer = () => document.getElementById('key-disclosure-container');



  return (
    <Dialog open={!props.inboxUnlocked} container={getContainer} style={{ position: 'absolute' }} BackdropProps={{ style: { position: 'absolute' } }}>
      <DialogTitle id="simple-dialog-title">Unlock [email protected] mailbox</DialogTitle>
      <DialogContent>
        <Box display={props.inboxUnlocked ? "none" : "block"}>
          <Typography>Add your private key to decrypt your inbox</Typography>

          <Box mt={2} mb={3}>
            <TextField placeholder="Private Key" fullWidth multiline rows={8} variant="outlined" onChange={onMailboxChange} />
          </Box>

          <Box textAlign="right">
            <Button variant="contained" className={classes.btn} onClick={onLoginClicked}>Decrypt</Button>
          </Box>
        </Box>
      </DialogContent>
    </Dialog >
  );
}