@mui/material#Button JavaScript Examples

The following examples show how to use @mui/material#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: index.js    From fireact with MIT License 6 votes vote down vote up
DataDelete = ({id, handleDeletion}) => {

    const [open, setOpen] = useState(false);

    return (
        <>
            <Button variant="contained" color="error" onClick={() => setOpen(true)}>
                Delete
            </Button>
            <Dialog onClose={() => setOpen(false)} open={open}>
                <DialogTitle>Delete</DialogTitle>
                <Box p={3}>
                    Confirm deletion?
                    <Stack direction="row" spacing={1} mt={2}>
                        <Button variant="contained" color="error" onClick={() => handleDeletion(id)}>Yes</Button>
                        <Button variant="contained" color="secondary" onClick={() => setOpen(false)}>Cancel</Button>
                    </Stack>
                </Box>
            </Dialog>
        </>
    )
}
Example #2
Source File: SubscriptionInfo.js    From react-saas-template with MIT License 6 votes vote down vote up
function SubscriptionInfo(props) {
  const { classes, openAddBalanceDialog } = props;
  return (
    <Toolbar className={classes.toolbar}>
      <ListItemText primary="Status" secondary="Premium Account" />
      <Button
        variant="contained"
        color="secondary"
        onClick={openAddBalanceDialog}
        disableElevation
      >
        Add Balance
      </Button>
    </Toolbar>
  );
}
Example #3
Source File: Page404.js    From Django-REST-Framework-React-BoilerPlate with MIT License 6 votes vote down vote up
// ----------------------------------------------------------------------

export default function Page404() {
  return (
    <Page title="404 Page Not Found">
      <Container>
        <ContentStyle sx={{ textAlign: 'center', alignItems: 'center' }}>
          <Typography variant="h3" paragraph>
            Sorry, page not found!
          </Typography>

          <Typography sx={{ color: 'text.secondary' }}>
            Sorry, we couldn’t find the page you’re looking for. Perhaps you’ve mistyped the URL? Be
            sure to check your spelling.
          </Typography>

          <Box
            component="img"
            src="/static/illustrations/illustration_404.svg"
            sx={{ height: 260, mx: 'auto', my: { xs: 5, sm: 10 } }}
          />

          <Button to="/" size="large" variant="contained" component={RouterLink}>
            Go to Home
          </Button>
        </ContentStyle>
      </Container>
    </Page>
  );
}
Example #4
Source File: ConfirmRestartStop.js    From admin-web with GNU Affero General Public License v3.0 6 votes vote down vote up
render() {
    const { t, open, handleConfirm, onClose, action, service } = this.props;

    return (
      <Dialog
        onClose={onClose}
        open={open}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>Are you sure you want to {action} {service?.name || 'this service'}?</DialogTitle>
        <DialogActions>
          <Button
            onClick={onClose}
            color="secondary"
          >
            {t('Cancel')}
          </Button>
          <Button
            onClick={handleConfirm}
            variant="contained"
            color="primary"
          >
            {t('Confirm')}
          </Button>
        </DialogActions>
      </Dialog>
    );
  }
Example #5
Source File: Todos.jsx    From CRM with Apache License 2.0 6 votes vote down vote up
AddColumnModal = ({
  addColumnModal,
  setAddColumnModal,
  handleAddColumn,
}) => {
  const [value, setValue] = useState("");
  return (
    <CustomModal
      open={addColumnModal}
      onClose={() => setAddColumnModal(false)}
      title="Add Column"
    >
      <CustomDarkInput
        label="Column Name"
        size="small"
        placeholder="ex: Production"
        fullWidth
        value={value}
        onChange={(e) => setValue(e.target.value)}
        autoFocus
      />

      <Button
        onClick={() => handleAddColumn(value)}
        variant="contained"
        size="small"
        className="mt-3"
      >
        Add Column
      </Button>
    </CustomModal>
  );
}
Example #6
Source File: ConfirmationDialog.jsx    From matx-react with MIT License 6 votes vote down vote up
StyledButton = styled(Button)(({ theme }) => ({
  margin: '8px',
  paddingLeft: '24px',
  paddingRight: '24px',
  overflow: 'hidden',
  borderRadius: '300px',
  transition: 'all 250ms',
  '&.yesBtn': {
    '&:hover': {
      color: '#ffffff',
      background: `${theme.palette.primary.main} !important`,
      backgroundColor: `${theme.palette.primary.main} !important`,
      fallbacks: [{ color: 'white !important' }],
    },
  },
  '&.noBtn': {
    '&:hover': {
      color: '#ffffff',
      background: `${theme.palette.secondary.main} !important`,
      backgroundColor: `${theme.palette.secondary.main} !important`,
      fallbacks: [{ color: 'white !important' }],
    },
  },
}))
Example #7
Source File: index.js    From zoomkoding-gatsby-blog with BSD Zero Clause License 6 votes vote down vote up
function PostCardColumn({ posts, showMoreButton, moreUrl }) {
  const onMoreButtonClick = useCallback(() => {
    navigate(moreUrl);
  }, [moreUrl]);

  return (
    <div className="post-card-column-wrapper">
      <div className="post-card-column">
        {posts.map((post, index) => (
          <PostCard key={index} post={post} />
        ))}
        {showMoreButton && (
          <Button
            className="more-post-card-button"
            onClick={onMoreButtonClick}
            variant="contained"
            disableElevation
          >
            More
          </Button>
        )}
      </div>
    </div>
  );
}
Example #8
Source File: SavedFilters.jsx    From Edlib with GNU General Public License v3.0 5 votes vote down vote up
SavedFilters = ({ savedFilterData, setShowDelete, filterUtils }) => {
    const { t } = useTranslation();
    const { classes } = useStyles();

    return (
        <>
            <List
                dense
                component="div"
                disablePadding
                className={classes.nested}
            >
                {savedFilterData.map((savedFilter) => {
                    return (
                        <ListItem
                            key={savedFilter.id}
                            button
                            dense
                            onClick={() =>
                                filterUtils.setFilterFromChoices(
                                    savedFilter.choices
                                )
                            }
                        >
                            <ListItemIcon
                                classes={{
                                    root: classes.listItemIcon,
                                }}
                            >
                                <Checkbox
                                    size="small"
                                    edge="start"
                                    checked={filterUtils.areFiltersAndChoicesIdentical(
                                        savedFilter.choices
                                    )}
                                    tabIndex={-1}
                                    disableRipple
                                    color="primary"
                                    classes={{
                                        root: classes.checkboxRoot,
                                    }}
                                />
                            </ListItemIcon>
                            <ListItemText primary={savedFilter.name} />
                        </ListItem>
                    );
                })}
                <ListItem dense>
                    <Box>
                        <Button
                            color="primary"
                            variant="outlined"
                            onClick={() => setShowDelete(true)}
                            size="small"
                            disabled={savedFilterData.length === 0}
                        >
                            {t('delete')}
                        </Button>
                    </Box>
                </ListItem>
            </List>
        </>
    );
}
Example #9
Source File: index.js    From fireact with MIT License 5 votes vote down vote up
DataCreate = ({schema, validation, handleCreation, success, children}) => {
    const mountedRef = useRef(true);

    const [inSubmit, setInSubmit] = useState(false);
    const [result, setResult] = useState({
        response: null,
        error: null
    });

    useEffect(() => {
        return () => { 
            mountedRef.current = false
        }
    },[]);

    return (
        <form onSubmit={e => {
            e.preventDefault();
            setInSubmit(true);
            if(validation()){
                let data = {};
                schema.forEach(field => {
                    data[field.name] = e.target.elements[field.name][field.prop]
                });
                handleCreation(data).then(res => {
                    if (!mountedRef.current) return null
                    setResult({
                        response: true,
                        error: null
                    });
                    setInSubmit(false);
                }).catch(err => {
                    if (!mountedRef.current) return null
                    setResult({
                        response: false,
                        error: err
                    });
                    setInSubmit(false);
                })
            }else{
                setResult({
                    response: false,
                    error: 'Please fill in the form in the correct format.'
                })
                setInSubmit(false);
            }
            
        }}>
            <Paper>
                <Box p={2}>
                    <Stack spacing={3}>
                        {result.response?(
                            <>{success}</>
                        ):(
                            <>
                            {result.response === false && 
                                <Alert severity="error">{result.error}</Alert>
                            }
                            {children}
                            <Stack direction="row" spacing={1} mt={2}>
                                <Button variant="contained" type="submit" disabled={inSubmit}>{inSubmit && <Loader />} Create</Button>
                            </Stack>
                            </>
                        )}
                    </Stack>
                </Box>
            </Paper>
        </form>
    )
}
Example #10
Source File: CookieConsent.js    From react-saas-template with MIT License 5 votes vote down vote up
function CookieConsent(props) {
  const { classes, handleCookieRulesDialogOpen } = props;
  const [isVisible, setIsVisible] = useState(false);

  const openOnEuCountry = useCallback(() => {
    fetchIpData
      .then((data) => {
        if (
          data &&
          data.country &&
          !europeanCountryCodes.includes(data.country)
        ) {
          setIsVisible(false);
        } else {
          setIsVisible(true);
        }
      })
      .catch(() => {
        setIsVisible(true);
      });
  }, [setIsVisible]);

  /**
   * Set a persistent cookie
   */
  const onAccept = useCallback(() => {
    Cookies.set("remember-cookie-snackbar", "", {
      expires: 365,
    });
    setIsVisible(false);
  }, [setIsVisible]);

  useEffect(() => {
    if (Cookies.get("remember-cookie-snackbar") === undefined) {
      openOnEuCountry();
    }
  }, [openOnEuCountry]);

  return (
    <Snackbar
      className={classes.snackbarContent}
      open={isVisible}
      message={
        <Typography className="text-white">
          We use cookies to ensure you get the best experience on our website.{" "}
        </Typography>
      }
      action={
        <Fragment>
          <Box mr={1}>
            <Button color="primary" onClick={handleCookieRulesDialogOpen}>
              More details
            </Button>
          </Box>
          <Button color="primary" onClick={onAccept}>
            Got it!
          </Button>
        </Fragment>
      }
    />
  );
}
Example #11
Source File: Searchbar.js    From Django-REST-Framework-React-BoilerPlate with MIT License 5 votes vote down vote up
// ----------------------------------------------------------------------

export default function Searchbar() {
  const [isOpen, setOpen] = useState(false);

  const handleOpen = () => {
    setOpen((prev) => !prev);
  };

  const handleClose = () => {
    setOpen(false);
  };

  return (
    <ClickAwayListener onClickAway={handleClose}>
      <div>
        {!isOpen && (
          <IconButton onClick={handleOpen}>
            <Iconify icon="eva:search-fill" width={20} height={20} />
          </IconButton>
        )}

        <Slide direction="down" in={isOpen} mountOnEnter unmountOnExit>
          <SearchbarStyle>
            <Input
              autoFocus
              fullWidth
              disableUnderline
              placeholder="Search…"
              startAdornment={
                <InputAdornment position="start">
                  <Iconify icon="eva:search-fill" sx={{ color: 'text.disabled', width: 20, height: 20 }} />
                </InputAdornment>
              }
              sx={{ mr: 1, fontWeight: 'fontWeightBold' }}
            />
            <Button variant="contained" onClick={handleClose}>
              Search
            </Button>
          </SearchbarStyle>
        </Slide>
      </div>
    </ClickAwayListener>
  );
}
Example #12
Source File: AddFolder.js    From admin-web with GNU Affero General Public License v3.0 5 votes vote down vote up
render() {
    const { classes, t, open, onClose, Users } = this.props;
    const { displayname, owners, container, comment, loading, autocompleteInput } = this.state;

    return (
      <Dialog
        onClose={onClose}
        open={open}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>{t('addHeadline', { item: 'Folder' })}</DialogTitle>
        <DialogContent style={{ minWidth: 400 }}>
          <FormControl className={classes.form}>
            <TextField 
              label={t("Folder name")}
              value={displayname}
              onChange={this.handleInput('displayname')}
              className={classes.input}
              autoFocus
              required
            />
            <TextField
              select
              className={classes.input}
              label={t("Container")}
              fullWidth
              value={container || ''}
              onChange={this.handleInput('container')}
            >
              {this.types.map((type, key) => (
                <MenuItem key={key} value={type.ID}>
                  {type.name}
                </MenuItem>
              ))}
            </TextField>
            <TextField 
              className={classes.input} 
              label={t("Comment")} 
              fullWidth
              multiline
              rows={4}
              value={comment}
              variant="outlined"
              onChange={this.handleInput('comment')}
            />
            <MagnitudeAutocomplete
              multiple
              value={owners || []}
              filterAttribute={'username'}
              inputValue={autocompleteInput}
              onChange={this.handleAutocomplete('owners')}
              className={classes.input} 
              options={Users || []}
              onInputChange={this.handleInput('autocompleteInput')}
              label={t('Owners')}
              placeholder={t("Search domains")  + "..."}
            />
          </FormControl>
        </DialogContent>
        <DialogActions>
          <Button
            onClick={onClose}
            color="secondary"
          >
            Cancel
          </Button>
          <Button
            onClick={this.handleAdd}
            variant="contained"
            color="primary"
            disabled={!displayname || loading}
          >
            {loading ? <CircularProgress size={24}/> : 'Add'}
          </Button>
        </DialogActions>
      </Dialog>
    );
  }
Example #13
Source File: MyButton.js    From SimpleWeather with MIT License 5 votes vote down vote up
MyButton = ({children, ...props}) => {
    return (
        <Button {...props}>
            {children}
        </Button>
    );
}
Example #14
Source File: Todos.jsx    From CRM with Apache License 2.0 5 votes vote down vote up
AddCardModal = ({
  addCardModal,
  setAddCardModal,
  handleAddCard,
  column,
  inputs,
  setInputs,
  handleInputs,
}) => {
  // const [value, setValue] = useState("");

  return (
    <CustomModal
      open={addCardModal}
      onClose={() => setAddCardModal(false)}
      title="Add Task"
    >
      <CustomDarkInput
        label="Task Title"
        size="small"
        placeholder="ex: Production"
        fullWidth
        name="title"
        value={inputs.title}
        onChange={handleInputs}
      />
      <CustomSunEditor
        inputs={inputs}
        setInputs={setInputs}
        name="description"
      />
      <CustomDarkInput label="Priority" size="small" fullWidth />
      <CustomDarkInput
        label="Label"
        size="small"
        placeholder="ex: Production"
        fullWidth
      />
      <CustomDarkInput
        label="Estimate in days"
        size="small"
        placeholder="ex: Production"
        fullWidth
      />
      <CustomDarkInput
        label="Start Date"
        size="small"
        placeholder="ex: Production"
        fullWidth
      />

      <Button
        onClick={() => handleAddCard(column)}
        variant="contained"
        size="small"
        className="mt-3"
      >
        Add Task
      </Button>
    </CustomModal>
  );
}
Example #15
Source File: column-order.js    From react-table-library with MIT License 5 votes vote down vote up
Component = () => {
  const data = { nodes };

  const materialTheme = getTheme(DEFAULT_OPTIONS);
  const theme = useTheme(materialTheme);

  const [columns, setColumns] = React.useState([
    { label: 'Task', renderCell: (item) => item.name },
    {
      label: 'Deadline',
      renderCell: (item) =>
        item.deadline.toLocaleDateString('en-US', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
        }),
    },
    { label: 'Type', renderCell: (item) => item.type },
    {
      label: 'Complete',
      renderCell: (item) => item.isComplete.toString(),
    },
    { label: 'Tasks', renderCell: (item) => item.nodes?.length },
  ]);

  const handleOrder = () => {
    setColumns([...columns].sort(() => 0.5 - Math.random()));
  };

  return (
    <>
      <Button variant="contained" onClick={handleOrder}>
        Shuffle
      </Button>
      <br />

      <CompactTable columns={columns} data={data} theme={theme} />

      <br />
      <DocumentationSee anchor={'Features/' + key} />
    </>
  );
}
Example #16
Source File: AppButton.jsx    From matx-react with MIT License 5 votes vote down vote up
StyledButton = styled(Button)(({ theme }) => ({
  margin: theme.spacing(1),
}))
Example #17
Source File: LoginForm.js    From react-admin-amplify-demo with MIT License 4 votes vote down vote up
LoginForm = (props) => {
  const { redirectTo, className } = props;
  const [loading, setLoading] = useSafeSetState(false);
  const login = useLogin();
  const translate = useTranslate();
  const notify = useNotify();
  const [demoUser, setDemoUser] = useState(null);

  useEffect(() => {
    if (demoUser) {
      return;
    }

    async function getDemoUser() {
      const userData = await API.graphql({
        query: getUser,
        variables: { id: "demo" },
        authMode: "AWS_IAM",
      });

      const { username, password } = userData.data.getUser;

      setDemoUser({ username, password });
    }

    getDemoUser();
  });

  if (!demoUser) {
    return null;
  }

  const submit = (values) => {
    setLoading(true);
    login(values, redirectTo)
      .then(() => {
        setLoading(false);
      })
      .catch((error) => {
        setLoading(false);
        notify(
          typeof error === "string"
            ? error
            : typeof error === "undefined" || !error.message
            ? "ra.auth.sign_in_error"
            : error.message,
          {
            type: "warning",
            messageArgs: {
              _:
                typeof error === "string"
                  ? error
                  : error && error.message
                  ? error.message
                  : undefined,
            },
          }
        );
      });
  };

  return (
    <StyledForm
      onSubmit={submit}
      mode="onChange"
      noValidate
      className={className}
      defaultValues={demoUser}
    >
      <CardContent className={LoginFormClasses.content}>
        <TextInput
          autoFocus
          source="username"
          label={translate("ra.auth.username")}
          validate={required()}
          fullWidth
        />
        <TextInput
          source="password"
          label={translate("ra.auth.password")}
          type="password"
          autoComplete="current-password"
          validate={required()}
          fullWidth
        />

        <Button
          variant="contained"
          type="submit"
          color="primary"
          disabled={loading}
          fullWidth
          className={LoginFormClasses.button}
        >
          {loading ? (
            <CircularProgress
              className={LoginFormClasses.icon}
              size={19}
              thickness={3}
            />
          ) : (
            translate("ra.auth.sign_in")
          )}
        </Button>
      </CardContent>
    </StyledForm>
  );
}
Example #18
Source File: index.jsx    From Edlib with GNU General Public License v3.0 4 votes vote down vote up
ContentExplorerHeader = ({ onClose, getUrl }) => {
    const { t } = useTranslation();
    const { classes } = useStyles();
    const location = useLocation();
    const history = useHistory();
    const { enableDoku, inMaintenanceMode } = useConfigurationContext();
    const { getUserConfig } = useEdlibComponentsContext();

    const isActive = (path) => {
        let paths = [path];

        if (Array.isArray(path)) {
            paths = [...path];
        }

        return paths.some((path) =>
            matchPath(location.pathname, {
                path,
                exact: false,
            })
        );
    };

    const enabledTypes =
        getUserConfig('enabledResourceTypes') || Object.values(resourceEditors);

    const isEditorEnabled = (type) => enabledTypes.indexOf(type) !== -1;

    const editorMapping = {
        [resourceEditors.H5P]: {
            link: getUrl('/resources/new/contentauthor?group=h5p'),
            label: t('Interaktivitet'),
        },
        [resourceEditors.QUESTION_SET]: {
            link: getUrl('/resources/new/contentauthor?group=questionset'),
            label: t('Spørsmål'),
        },
        // [resourceEditors.ARTICLE]: {
        //     link: getUrl('/resources/new/contentauthor?group=article'),
        //     label: t('Tekst'),
        // },
        // [resourceEditors.EMBED]: {
        //     link: '/resources/new/url',
        //     label: 'Link',
        // },
        [resourceEditors.DOKU]: {
            link: getUrl('/resources/new/doku'),
            label: 'EdStep',
        },
    };

    const activatedEditorsList = Object.entries(editorMapping)
        .filter(([type]) => isEditorEnabled(type))
        .filter(([type]) => {
            switch (type) {
                case resourceEditors.DOKU:
                    return enableDoku;
                default:
                    return true;
            }
        });
    //******************************************************************************
    //************ New Component ***************************************************
    //******************************************************************************
    const [anchorEl, setAnchorEl] = React.useState(null);
    const open = Boolean(anchorEl);

    const handleMenu = (event) => {
        setAnchorEl(event.currentTarget);
    };

    const handleClose = () => {
        setAnchorEl(null);
    };

    const buttonClasses = (active) =>
        cn(classes.headerButton, {
            [classes.selectedButton]: active,
        });

    return (
        <AppBar position="static" className={classes.appBar}>
            <Toolbar className={classes.toolbar}>
                <div>
                    <img
                        className={classes.logo}
                        src={logoUrl}
                        alt="edlib logo"
                    />
                </div>
                {!inMaintenanceMode && (
                    <div className={classes.links}>
                        {activatedEditorsList.length > 1 && (
                            <div>
                                <Button
                                    aria-controls="menu-appbar"
                                    aria-haspopup="true"
                                    onClick={handleMenu}
                                    color="inherit"
                                    startIcon={<AddCircleRounded />}
                                    sx={{
                                        color: isActive([
                                            getUrl('/resources/new'),
                                            getUrl('/link-author'),
                                            getUrl('/doku-author'),
                                        ])
                                            ? 'secondary.main'
                                            : 'default',
                                    }}
                                    className={classes.headerButton}
                                >
                                    {t('Opprett innhold')}
                                </Button>
                                <Menu
                                    id="menu-appbar"
                                    anchorEl={anchorEl}
                                    keepMounted
                                    getContentAnchorEl={null}
                                    anchorOrigin={{
                                        vertical: 'bottom',
                                        horizontal: 'center',
                                    }}
                                    transformOrigin={{
                                        vertical: 'top',
                                        horizontal: 'center',
                                    }}
                                    open={open}
                                    onClose={handleClose}
                                >
                                    {activatedEditorsList.map(
                                        ([type, { link, label }]) => (
                                            <MenuItem
                                                onClick={() => {
                                                    history.push(link);
                                                    handleClose();
                                                }}
                                                key={type}
                                            >
                                                {label}
                                            </MenuItem>
                                        )
                                    )}
                                </Menu>
                            </div>
                        )}
                        {activatedEditorsList.length === 1 && (
                            <div>
                                <Button
                                    onClick={() => {
                                        history.push(
                                            activatedEditorsList[0][1].link
                                        );
                                        handleClose();
                                    }}
                                    color="inherit"
                                    startIcon={<AddCircleRounded />}
                                    sx={{
                                        color: isActive(
                                            activatedEditorsList[0][1].link
                                        )
                                            ? 'secondary.main'
                                            : 'default',
                                    }}
                                    className={classes.headerButton}
                                >
                                    {t('Opprett innhold')}
                                </Button>
                            </div>
                        )}
                        <div>
                            <Button
                                onClick={() => {
                                    history.push(getUrl('/shared-content'));
                                    handleClose();
                                }}
                                color="inherit"
                                startIcon={<ShoppingCart />}
                                sx={{
                                    color: isActive(getUrl('/shared-content'))
                                        ? 'secondary.main'
                                        : 'default',
                                }}
                                className={classes.headerButton}
                            >
                                {t('Delt innhold')}
                            </Button>
                        </div>
                        <div>
                            <Button
                                onClick={() => {
                                    history.push(getUrl('/my-content'));
                                    handleClose();
                                }}
                                color="inherit"
                                startIcon={<Home />}
                                sx={{
                                    color: isActive(getUrl('/my-content'))
                                        ? 'secondary.main'
                                        : 'default',
                                }}
                                className={classes.headerButton}
                            >
                                {t('Mitt innhold')}
                            </Button>
                        </div>
                    </div>
                )}
                {onClose ? (
                    <div className={classes.close}>
                        <Close onClick={onClose} />
                    </div>
                ) : (
                    <div>&nbsp</div>
                )}
            </Toolbar>
        </AppBar>
    );
}
Example #19
Source File: index.js    From fireact with MIT License 4 votes vote down vote up
Home = () => {
    const title = 'My Accounts';
    const history = useHistory();   

    const { setBreadcrumb } = useContext(BreadcrumbContext);
    

    const [loading, setLoading] = useState(true);
    const [accounts, setAccounts] = useState([]);
    const mountedRef = useRef(true);

    const getAccounts = () => {
        setLoading(true);
        let records = [];
        const accountsRef = FirebaseAuth.firestore().collection('accounts');
        let query = accountsRef.where('access', 'array-contains', FirebaseAuth.auth().currentUser.uid);
        query.get().then(accountSnapshots => {
            if (!mountedRef.current) return null
            accountSnapshots.forEach(account => {
                records.push({
                    'id': account.id,
                    'name': account.data().name,
                    'subscriptionStatus': account.data().subscriptionStatus
                });
            });
            setAccounts(records);
            setLoading(false);
        });
    }

    useEffect(() => {
        setBreadcrumb([
            {
                to: "/",
                text: "Home",
                active: false
            },
            {
                to: null,
                text: title,
                active: true
            }
        ]);
        getAccounts();
    },[setBreadcrumb]);

    useEffect(() => {
        return () => { 
            mountedRef.current = false
        }
    },[]);

    return (
        <>
            {accounts.length > 0 ? (
                <>
                    <div style={{marginTop: '20px', marginBottom: '20px', textAlign: 'right'}}>
                        <Button onClick={() => history.push('/new-account')} color="primary" variant="contained"><i className="fa fa-plus"></i> Add Account</Button>
                    </div>
                    <Grid container spacing={3}>
                    {accounts.map((account, i) => 
                        <Grid container item xs={12} md={3} key={i}>
                            <Card key={account.id} style={{width: '100%'}}>
                                <CardHeader title={account.name}/>
                                <CardActions>
                                    {account.subscriptionStatus?(
                                        <Button size="small" color="primary" onClick={() => history.push('/account/'+account.id+'/')}>Account Overview</Button>
                                    ):(
                                        <Button size="small" color="warning" onClick={() => history.push('/account/'+account.id+'/billing/plan')}>Activate the account</Button>
                                    )}
                                </CardActions>
                            </Card>
                        </Grid>
                    )}
                    </Grid>
                </>
            ) : (
                <>
                    {(loading) ? (
                        <Loader text="loading accounts..."></Loader>
                    ):(
                        <Redirect to="/new-account"></Redirect>
                    )}
                </>
            )}
        </>

    )
}
Example #20
Source File: Settings1.js    From react-saas-template with MIT License 4 votes vote down vote up
function Settings1(props) {
  const { classes, pushMessageToSnackbar } = props;
  const [isSaveLoading, setIsSaveLoading] = useState(false);
  const [isDefaultLoading, setIsDefaultLoading] = useState(false);
  const [option1, setOption1] = useState("None");
  const [option2, setOption2] = useState("None");
  const [option3, setOption3] = useState("None");
  const [option4, setOption4] = useState("None");
  const [option5, setOption5] = useState("2 Days");
  const [option6, setOption6] = useState(7500);

  const handleChange = useCallback(
    (event) => {
      const { name, value } = event.target;
      if (name === "option6") {
        if (value > 7500 || value < 1000) {
          return;
        }
      }
      switch (name) {
        case "option1": {
          setOption1(value);
          break;
        }
        case "option2": {
          setOption2(value);
          break;
        }
        case "option3": {
          setOption3(value);
          break;
        }
        case "option4": {
          setOption4(value);
          break;
        }
        case "option5": {
          setOption5(value);
          break;
        }
        case "option6": {
          setOption6(value);
          break;
        }
        default:
          throw new Error("No branch selected in switch statement.");
      }
    },
    [setOption1, setOption2, setOption3, setOption4, setOption5, setOption6]
  );

  const resetState = useCallback(() => {
    setIsSaveLoading(false);
    setIsDefaultLoading(false);
    setOption1("None");
    setOption2("None");
    setOption3("None");
    setOption4("None");
    setOption5("2 Days");
    setOption6(7500);
  }, [
    setIsSaveLoading,
    setIsDefaultLoading,
    setOption1,
    setOption2,
    setOption3,
    setOption4,
    setOption5,
    setOption6,
  ]);

  const onSetDefault = useCallback(() => {
    setIsDefaultLoading(true);
    setTimeout(() => {
      pushMessageToSnackbar({
        text: "Your settings have been reset to default",
      });
      resetState();
    }, 1500);
  }, [pushMessageToSnackbar, resetState]);

  const onSubmit = useCallback(() => {
    setIsSaveLoading(true);
    setTimeout(() => {
      pushMessageToSnackbar({
        text: "Your settings have been saved",
      });
      setIsSaveLoading(false);
    }, 1500);
  }, [setIsSaveLoading, pushMessageToSnackbar]);

  const inputs = [
    {
      state: option1,
      label: "Option 1",
      stateName: "option1",
    },
    {
      state: option2,
      label: "Option 2",
      stateName: "option2",
    },
    {
      state: option3,
      label: "Option 3",
      stateName: "option3",
    },
    {
      state: option4,
      label: "Option 4",
      stateName: "option4",
    },
  ];

  return (
    <Accordion>
      <AccordionSummary expandIcon={<ExpandMoreIcon />}>
        <Typography>Settings 1</Typography>
      </AccordionSummary>
      <AccordionDetails className={classes.dBlock}>
        <List disablePadding>
          <Bordered disableVerticalPadding disableBorderRadius>
            {inputs.map((element, index) => (
              <ListItem
                className="listItemLeftPadding"
                disableGutters
                divider
                key={index}
              >
                <ListItemText>
                  <Typography variant="body2">{element.label}</Typography>
                </ListItemText>
                <FormControl variant="outlined">
                  <ListItemSecondaryAction
                    className={classes.ListItemSecondaryAction}
                  >
                    <Select
                      value={element.state}
                      onChange={handleChange}
                      input={
                        <OutlinedInput
                          name={element.stateName}
                          labelWidth={0}
                          className={classes.numberInput}
                          classes={{ input: classes.numberInputInput }}
                        />
                      }
                      MenuProps={{ disableScrollLock: true }}
                    >
                      {inputOptions.map((innerElement) => (
                        <MenuItem value={innerElement} key={innerElement}>
                          {innerElement}
                        </MenuItem>
                      ))}
                    </Select>
                  </ListItemSecondaryAction>
                </FormControl>
              </ListItem>
            ))}
            <ListItem className="listItemLeftPadding" disableGutters divider>
              <ListItemText>
                <Typography variant="body2">Option 5</Typography>
              </ListItemText>
              <FormControl variant="outlined">
                <ListItemSecondaryAction
                  className={classes.ListItemSecondaryAction}
                >
                  <Select
                    value={option5}
                    onChange={handleChange}
                    input={
                      <OutlinedInput
                        name="option5"
                        labelWidth={0}
                        className={classes.numberInput}
                        classes={{ input: classes.numberInputInput }}
                      />
                    }
                    MenuProps={{ disableScrollLock: true }}
                  >
                    {[
                      "Always",
                      "6 Hours",
                      "12 Hours",
                      "1 Day",
                      "2 Days",
                      "3 Days",
                      "1 Week",
                    ].map((element) => (
                      <MenuItem value={element} key={element}>
                        {element}
                      </MenuItem>
                    ))}
                  </Select>
                </ListItemSecondaryAction>
              </FormControl>
            </ListItem>
            <ListItem className="listItemLeftPadding" disableGutters>
              <ListItemText>
                <Typography variant="body2">Option 6</Typography>
              </ListItemText>
              <FormControl variant="outlined">
                <ListItemSecondaryAction
                  className={classes.ListItemSecondaryAction}
                >
                  <OutlinedInput
                    labelWidth={0}
                    name="option6"
                    value={option6}
                    type="number"
                    onChange={handleChange}
                    className={classes.numberInput}
                    classes={{ input: classes.numberInputInput }}
                    inputProps={{ step: 20 }}
                  />
                </ListItemSecondaryAction>
              </FormControl>
            </ListItem>
          </Bordered>
        </List>
      </AccordionDetails>
      <AccordionDetails className={classes.accordionDetails}>
        <Box mr={1}>
          <Button
            onClick={onSetDefault}
            disabled={isSaveLoading || isDefaultLoading}
          >
            Default {isDefaultLoading && <ButtonCircularProgress />}
          </Button>
        </Box>
        <Button
          variant="contained"
          color="secondary"
          disabled={isSaveLoading || isDefaultLoading}
          onClick={onSubmit}
        >
          Save {isSaveLoading && <ButtonCircularProgress />}
        </Button>
      </AccordionDetails>
    </Accordion>
  );
}