@material-ui/core#TextField JavaScript Examples

The following examples show how to use @material-ui/core#TextField. 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: test-material-ui-utils.test.js    From flame-coach-web with MIT License 7 votes vote down vote up
ElementSelect = () => {
    return (
        <TextField
            select
            data-testid='testId'
            value='0'>
            <MenuItem key='0' value='0'>Option 1</MenuItem>
            <MenuItem key='1' value='1'>Option 2</MenuItem>
        </TextField>
    );
}
Example #2
Source File: Footer.js    From bunk-manager-mern with MIT License 6 votes vote down vote up
MyTextField = withStyles({            //textField type 1    
  root: {
    "& label.Mui-focused": {
      color: "white",
    },
    "& .MuiOutlinedInput-root": {
      "& input:valid + fieldset": {
        borderColor: "white",
        borderWidth: 3,
        color: "white",
      },
    },
  },
})(TextField)
Example #3
Source File: BoardTitle.js    From TrelloClone with MIT License 6 votes vote down vote up
BoardTitle = ({ board }) => {
  const [editing, setEditing] = useState(false);
  const [title, setTitle] = useState(board.title);
  const dispatch = useDispatch();

  useEffect(() => {
    setTitle(board.title);
  }, [board.title]);

  const onSubmit = async (e) => {
    e.preventDefault();
    dispatch(renameBoard(board._id, { title }));
    setEditing(false);
  };

  return !editing ? (
    <h2 className='board-title' onClick={() => setEditing(true)}>
      {board.title}
    </h2>
  ) : (
    <form className='board-title-form' onSubmit={(e) => onSubmit(e)}>
      <TextField
        variant='outlined'
        required
        value={title}
        size='small'
        onChange={(e) => setTitle(e.target.value)}
      />
    </form>
  );
}
Example #4
Source File: Login.js    From connect-4-online-multiplayer with MIT License 6 votes vote down vote up
export default function Login() {
  const iRef = useRef();
  const setUser = useContext(DispatchUserContext);
  function handleSubmit(e) {
    e.preventDefault();
    setUser({ id: v4(), name: iRef.current.value });
  }

  return (
    <Container maxWidth="sm">
      <Box textAlign="center" pt={4}>
        <form onSubmit={handleSubmit}>
          {/* <label>Name:</label> */}
          <TextField
            id="outlined-basic"
            label="Enter your name"
            variant="outlined"
            inputRef={iRef}
            required
          />
          <Box py={4}>
            <Button type="submit" variant="contained" color="primary">
              Submit
            </Button>
          </Box>
        </form>
      </Box>
    </Container>
  );
}
Example #5
Source File: reviewGeneralInfoFormTemplate.js    From resumeker-fe with MIT License 6 votes vote down vote up
function ReviewGeneralInfoFormTemplate(props) {

    const classes = useStyles();

    return(
        <div className={classes.textField}>
              <TextField
                variant="outlined"
                margin="normal"
                fullWidth
                required
                name="name"
                label="Name"
                id="name"
                onChange={props.onChange}
                value={props.info.name}
              />
              <TextField
                variant="outlined"
                margin="normal"
                required
                fullWidth
                name="email"
                label="Email"
                id="email"
                onChange={props.onChange}
                value={props.info.email}
              />
        </div>
    )
}
Example #6
Source File: CssTextField.js    From usfm-grammar-online with MIT License 6 votes vote down vote up
export default function CssTextField(props) {
  return (
    <TextField
      InputLabelProps={{
        style: {
          height: "calc(100vh - 195px)",
        },
      }}
      inputProps={{
        style: {
          height: "calc(100vh - 195px)",
          overflow: "auto",
        },
      }}
      style={{
        height: "calc(100vh - 195px)",
        width: "100%",
      }}
      multiline
      variant="outlined"
      {...props}
    />
  );
}
Example #7
Source File: TextInput.js    From Quizzie with MIT License 6 votes vote down vote up
TextInput = withStyles({
	root: {
		'& label': {
			color: 'rgba(0,0,0,0.7)',
		},
		'& label.Mui-focused': {
			color: '#2980B9',
		},
		'& .MuiInput-underline:after': {
			borderBottomColor: '#2980B9',
		},
		'& .MuiInputBase-input': {
			color: 'black !important',
		},
		'& .MuiOutlinedInput-root': {
			'& fieldset': {
			  borderColor: 'rgba(0,0,0,0.7)',
			},
			'&:hover fieldset': {
			  borderColor: '#2980B9',
			},
			'&.Mui-focused fieldset': {
			  borderColor: '#2980B9',
			},
		  },
	}
})(TextField)
Example #8
Source File: signinform.js    From React-Messenger-App with MIT License 6 votes vote down vote up
render() {
    const { classes } = this.props;
    const { signInError, signInPassword, signInEmail } = this.state;
    return (
      <div>
        {signInError ? (
          <p>{signInError}</p>
        ) : (
          <div>
            <form onSubmit={this.onSignIn}>
              <div className={classes.handle}>
                <p>Sign In</p>
                <TextField
                  type="email"
                  required
                  placeholder="email"
                  value={signInEmail}
                  onChange={this.onchangeInputs("signInEmail")}
                />
                <br />
                <TextField
                  type="password"
                  required
                  placeholder="Password"
                  value={signInPassword}
                  onChange={this.onchangeInputs("signInPassword")}
                />
                <br />
                <Button type="submit" variant="contained" color="primary">
                  Sign In
                </Button>
              </div>
            </form>
          </div>
        )}
        ;
      </div>
    );
  }
Example #9
Source File: App.jsx    From image-stego with MIT License 6 votes vote down vote up
export default function App() {

  const [option, setOption] = useState('home');

  function handleClick(event) {

    const { name } = event.currentTarget;
    if (name === 'home') {
      setOption('home');
      document.getElementById('encoded-image').style.display = 'none';
    } else if (name === 'encode') {
      setOption('encode');
    } else if (name === 'decode') {
      setOption('decode');
    }
  }

  return (
    <div className='content'>
      <h1>IMAGE<span id="word"> STEGO</span></h1>
      {option === 'home' && <Button style={{margin: '1rem'}} name='encode' onClick={handleClick} variant="contained">Encode</Button>}
      {option === 'home' && <Button style={{margin: '1rem'}} name='decode' onClick={handleClick} variant="contained">Decode</Button>}
      {option === 'encode' && <TextField variant="outlined" multiline type="text" id="secret" name="secret" placeholder="Enter secret message" />}
      {option !== 'home' && <UploadButton />}
      {option === 'encode' && <Button style={{margin: '1rem'}} onClick={encode} variant="contained">Encode</Button>}
      {option === 'decode' && <Button style={{margin: '1rem'}} onClick={decode} variant="contained">Decode</Button>}
      {option !== 'home' && <Button style={{margin: '1rem'}} name='home' onClick={handleClick} variant="contained">Return</Button>}
      <img id="encoded-image" alt='encoded output'></img>
      <canvas id="canvas"></canvas>
    </div>
  );
}
Example #10
Source File: test-material-ui-utils.test.js    From flame-coach-web with MIT License 6 votes vote down vote up
ElementInput = () => {
    return (
        <TextField
            data-testid='testId'
            value='10' />
    );
}
Example #11
Source File: SearchInbox.js    From treetracker-admin-client with GNU Affero General Public License v3.0 6 votes vote down vote up
SearchInbox = ({ setSearch }) => {
  const { wrapForm, field } = useStyles();

  return (
    <form className={wrapForm} noValidate autoComplete="off">
      <TextField
        id="outlined-search"
        label="Search by name or ID ..."
        type="search"
        variant="filled"
        className={field}
        onChange={(e) => setSearch(e.target.value)}
      />
    </form>
  );
}
Example #12
Source File: CharacterDialog.jsx    From archeage-tools with The Unlicense 6 votes vote down vote up
render() {
    const { characters, characterId, open, onClose } = this.props;
    const { name, error } = this.state;
    const characterName = pathOr(null, [characterId])(characters);
    const validChar = !(characterId === null || characterName === null);

    return (
      <Dialog open={open} onClose={onClose}>
        <DialogTitle>
          {!validChar
            ? 'Add Character'
            : `Edit [${characterName}]`}
        </DialogTitle>
        <DialogContent>
          <form onSubmit={this.handleSave}>
            <TextField
              label="Character Name"
              value={name}
              onChange={this.handleChange}
              inputProps={{
                maxLength: 20,
              }}
              autoFocus
              error={Boolean(error)}
              helperText={error}
            />
          </form>
        </DialogContent>
        <DialogActions>
          {validChar &&
          <Button onClick={this.handleDelete} classes={{ label: 'text-red' }}>Delete</Button>}
          <Button onClick={onClose}>Cancel</Button>
          <Button color="primary" onClick={this.handleSave}>Confirm</Button>
        </DialogActions>
      </Dialog>
    );
  }
Example #13
Source File: BlogPostsSearch.js    From course-manager with MIT License 6 votes vote down vote up
export default function BlogPostsSearch({ posts }) {
  return (
    <RootStyle>
      <Autocomplete
        size="small"
        disablePortal
        popupIcon={null}
        options={posts}
        getOptionLabel={(post) => post.title}
        renderInput={(params) => (
          <TextField
            {...params}
            placeholder="Search post..."
            InputProps={{
              ...params.InputProps,
              startAdornment: (
                <>
                  <InputAdornment position="start">
                    <Box
                      component={Icon}
                      icon={searchFill}
                      sx={{
                        ml: 1,
                        width: 20,
                        height: 20,
                        color: 'text.disabled'
                      }}
                    />
                  </InputAdornment>
                  {params.InputProps.startAdornment}
                </>
              )
            }}
          />
        )}
      />
    </RootStyle>
  );
}
Example #14
Source File: FormikMuiFields.js    From reddish with MIT License 6 votes vote down vote up
TextInput = ({
  placeholder,
  label,
  type,
  required,
  fullWidth,
  InputProps,
  multiline,
  rows,
  rowsMax,
  variant,
  size,
  disabled,
  ...props
}) => {
  const [field, meta] = useField(props);
  const errorText = meta.error && meta.touched ? meta.error : '';

  return (
    <TextField
      placeholder={placeholder}
      label={label}
      type={type}
      InputProps={InputProps}
      required={required}
      fullWidth
      multiline={multiline}
      rows={rows}
      rowsMax={rowsMax}
      variant={variant}
      size={size}
      disabled={disabled}
      {...field}
      helperText={errorText}
      error={!!errorText}
    />
  );
}
Example #15
Source File: SearchTextField.js    From voicemail-for-amazon-connect with Apache License 2.0 6 votes vote down vote up
render() {
        let classes = this.props.classes;
        return (
            <Grid container direction={"row"} alignItems={"flex-end"} alignContent={"center"}>
                <Search className={classes.search}/>
                <Grid item>
                    <TextField
                        className={classes.textField}
                        placeholder={"Search"}
                        name="search"
                        value={this.state.searchValue}
                        onChange={this.handleSearchChange}
                    />
                </Grid>
                {this.props.showClearButton ?
                    <Cancel className={classes.clearSearch} onClick={() => {
                        this.updateSearch("")
                    }}/> :
                    null
                }
            </Grid>
        )
    }
Example #16
Source File: AddProductToCollection.js    From beluga with GNU General Public License v3.0 6 votes vote down vote up
function AddProductToCollection(props) {
  const { storeConfig, collection, handleChange } = props;

  const addProduct = product => {
    const newProducts = [...collection.products]
    newProducts.unshift(product.stripe_id);
    handleChange("products", newProducts);
  }

  if (!storeConfig) return (null);
  const eligableProducts = [...storeConfig.products]
    .filter(t => collection.products.indexOf(t.stripe_id) === -1)

  return (
    <div>
      <div style={{ margin: "40px 0" }}>
        <Autocomplete
          options={eligableProducts}
          getOptionLabel={product => product.name}
          style={{ width: 300 }}
          onChange={(e,o) => o && addProduct(o)}
          renderInput={params => (
            <TextField {...params} label="Add Product" variant="outlined" fullWidth />
          )}
        />
      </div>
      <EditableImageList
        storeConfig={storeConfig}
        products={collection.products}
        handleChange={handleChange}
      />
    </div>
  );
}
Example #17
Source File: AddComment.js    From clone-instagram-ui with MIT License 6 votes vote down vote up
AddComment = ({ onCommentChange }) => {
  return (
    <TextField
      style={{ display: 'flex' }}
      placeholder="Add a comment ..."
      onKeyDown={(event) =>
        handleTextFieldKeyDown(event, (value) => {
          onCommentChange(value);
        })
      }
    />
  );
}
Example #18
Source File: TagsManager.js    From Edlib with GNU General Public License v3.0 6 votes vote down vote up
renderTextInput(inputProps) {
        const {
            InputProps,
            classes,
            ref,
            ...other
        } = inputProps;

        return (
            <TextField
                InputProps={{
                    inputRef: ref,
                    classes: {
                        root: classes.inputRoot,
                    },
                    ...InputProps,
                }}
                {...other}
            />
        );
    }
Example #19
Source File: Header.jsx    From scholar-front-end with MIT License 6 votes vote down vote up
function Header() {



    const classes = useStyle();

    return (
        <div className={styles.header}>
            <div><Notification/></div>
            <div className={classes.defaultHeader}>
                <IconButton>
                <div className={styles.logo}><img className={styles.logoImage} src={require("../../data/logoUnfinished.jpg").default} alt="logo"/></div>
                </IconButton>
                <Button  className={classes.linkStyle}><CategoryIcon /></Button>
                <form noValidate autoComplete="off">
                        <TextField id="standard-basic" label="Search Courses" variant="filled" />
                </form>
                <Button> <ShoppingCart /> </Button>
                <div className={styles.signupOptions}>
                    <Link to="login">
                    <Button variant="contained"  color="primary" className={classes.root}>Login</Button>
                    </Link>
                    <Link to="signup">
                    <Button variant="contained" color="primary" className={classes.root}>Signup</Button>
                    </Link>
                </div>
            </div>
        </div>
    )
}
Example #20
Source File: KbSearch.js    From dataqa with GNU General Public License v3.0 6 votes vote down vote up
render() {
    const { classes } = this.props;

    return (
      <Autocomplete
        classes={{ inputRoot: classes.inputRoot }}
        options={this.state.options}
        getOptionLabel={option => option.name}
        onChange={this.addSuggestion}
        renderInput={params => <TextField
                                  {...params}
                                  label={""}
                                  required={false}
                               />
        }
        onInputChange={this.onInputChange}
        getOptionSelected={(value, option) => value.name == option.name}
        autoSelect={true}
        inputValue={this.state.inputValue}
        disableClearable={true}
        value={this.state.value}
      />
    )
  }
Example #21
Source File: metrics.js    From graphql-sample-apps with Apache License 2.0 6 votes vote down vote up
Metrics = () => {
  const {loading, error, data} = useQuery(query);
  const [newMetricName, setNewMetricName] = useState("");
  const [addMetric, { loading: mutationLoading }] = useMutation(addMetricMutation, {
    awaitRefetchQueries: true,
    refetchQueries: [{query}],
  });

  const metrics = data?.queryMetric || []

  return <>
    <Navbar title="Metrics" color="primary" />
    <Content>
      {loading && <Backdrop open={loading || mutationLoading} >
        <CircularProgress />
      </Backdrop>}
      {error && <Alert severity="error">Something Went Horribly Wrong</Alert>}
      <Card style={{ padding: 30 }}>
        <Typography>Here are the metrics currently configured:</Typography>
        <List>
          {metrics.map(({ name }, index) => <ListItem item key={index} sm={12} md={6} lg={3}>
            <Typography>{name}</Typography>
          </ListItem>)}
        </List>

        <TextField
          label="Add Metric"
          defaultValue={newMetricName}
          onChange={e => setNewMetricName(e.target.value)}
        />
        <UglyButton onClick={() => addMetric({ variables: { newMetricName } })} disabled={newMetricName === ""}>
          Add Metric
        </UglyButton>
      </Card>
    </Content>
  </>
}
Example #22
Source File: Footer.js    From bunk-manager-mern with MIT License 5 votes vote down vote up
MyTextField2 = withStyles({
  //textField type2
  root: {
    "& label.Mui-focused": {
      color: "white",
    },
  },
})(TextField)
Example #23
Source File: DeploymentNameModal.js    From akashlytics-deploy with GNU General Public License v3.0 5 votes vote down vote up
DeploymentNameModal = ({ dseq, onClose, onSaved, getDeploymentName }) => {
  const classes = useStyles();
  const formRef = useRef();
  const { enqueueSnackbar } = useSnackbar();
  const { handleSubmit, control, setValue } = useForm({
    defaultValues: {
      name: ""
    }
  });

  useEffect(() => {
    if (dseq) {
      const name = getDeploymentName(dseq);
      setValue("name", name || "");
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dseq, getDeploymentName]);

  const onSaveClick = (event) => {
    event.preventDefault();
    formRef.current.dispatchEvent(new Event("submit", { cancelable: true, bubbles: true }));
  };

  function onSubmit({ name }) {
    updateDeploymentLocalData(dseq, { name: name });

    enqueueSnackbar(<Snackbar title="Success!" iconVariant="success" />, { variant: "success", autoHideDuration: 1000 });

    onSaved();
  }

  return (
    <Dialog open={!!dseq} onClose={onClose} maxWidth="xs" fullWidth>
      <DialogTitle>Change Deployment Name {dseq ? `(${dseq})` : ""}</DialogTitle>
      <DialogContent dividers className={classes.dialogContent}>
        <form onSubmit={handleSubmit(onSubmit)} ref={formRef}>
          <FormControl fullWidth>
            <Controller
              control={control}
              name="name"
              render={({ field }) => {
                return <TextField {...field} autoFocus type="text" variant="outlined" label="Name" />;
              }}
            />
          </FormControl>
        </form>
      </DialogContent>
      <DialogActions className={classes.dialogActions}>
        <Button onClick={onClose}>Close</Button>
        <Button variant="contained" color="primary" onClick={onSaveClick}>
          Save
        </Button>
      </DialogActions>
    </Dialog>
  );
}
Example #24
Source File: CreateList.js    From TrelloClone with MIT License 5 votes vote down vote up
CreateList = () => {
  const [adding, setAdding] = useState(false);
  const [title, setTitle] = useState('');
  const dispatch = useDispatch();

  const formRef = useRef(null);
  useEffect(() => {
    formRef && formRef.current && formRef.current.scrollIntoView();
  }, [title]);

  const onSubmit = async (e) => {
    e.preventDefault();
    dispatch(addList({ title }));
    setTitle('');
  };

  return !adding ? (
    <div className='create-list-button'>
      <Button variant='contained' onClick={() => setAdding(true)}>
        + Add a list
      </Button>
    </div>
  ) : (
    <div ref={formRef} className='create-list-form'>
      <form onSubmit={(e) => onSubmit(e)}>
        <TextField
          variant='outlined'
          fullWidth
          margin='normal'
          required
          label='Enter list title'
          autoFocus
          value={title}
          onChange={(e) => setTitle(e.target.value)}
        />
        <div>
          <Button type='submit' variant='contained' color='primary'>
            Add List
          </Button>
          <Button
            onClick={() => {
              setAdding(false);
              setTitle('');
            }}
          >
            <CloseIcon />
          </Button>
        </div>
      </form>
    </div>
  );
}
Example #25
Source File: EditAnnouncementModal.js    From AdaptivApps-fe with MIT License 5 votes vote down vote up
function EditAnnouncementModal({ setAnnouncementOpen, announcement, setUpdateChat }) {
  const classes = useStyles();

  const [updateAnnouncement] = useMutation(UPDATE_ANNOUNCEMENT);

  const [updateTitle, setUpdateTitle] = useState(announcement.title);
  const [updateMessage, setUpdateMessage] = useState(announcement.message);
  
  const handleTitleChange = e => {
    setUpdateTitle(e.target.value);
  };

  const handleMessageChange = e => {
    setUpdateMessage(e.target.value);
  };

  // Send updated announcement to BE
  const onSubmit = async () => {
    await updateAnnouncement({
      variables: {
        id: announcement.id,
        title: updateTitle,
        message: updateMessage
      }
    });
    setAnnouncementOpen(false);
    setUpdateChat(true);
  };

  const closeModal = e => {
    e.preventDefault();
    setAnnouncementOpen(false);
  };

  return (
    <div className={classes.modal}>          
      <div className={classes.paper}>
        <Tooltip title="Cancel">
          <CloseIcon className={classes.closeModal} onClick={closeModal} />
        </Tooltip>
        <h2 id="transition-modal-title" className={classes.span}>Update Announcement</h2>
        <h3 className={classes.titles}>Announcement Title</h3>
        <div className={classes.titleDiv}>       
          <Box component="div" className={classes.titleInput}>
            <TextField
              variant="outlined"
              type="text"
              fullWidth
              name="announcementTitle"
              value={updateTitle}
              onChange={handleTitleChange} />
          </Box>
        </div>
        <h3 className={classes.titles}>Announcement Text</h3>
        <div className={classes.titleDiv}>
          <Box component="div" className={classes.titleInput}>
            <TextField
              variant="outlined"
              multiline={true}
              rows={2}
              rowsMax={4}
              fullWidth
              type="text"
              name="announcementText"
              value={updateMessage}
              onChange={handleMessageChange} />
          </Box>
        </div>      
        <div className={classes.buttonDiv}>
          <Tooltip title="Update Announcement">
            <Button variant="outlined" color="primary" onClick={onSubmit} className={classes.button}>
              Update Announcement
            </Button>
          </Tooltip>
        </div>
      </div>
    </div>
  )
}
Example #26
Source File: generalInfoFormTemplate.js    From resumeker-fe with MIT License 5 votes vote down vote up
function GeneralInfoFormTemplate(props) {

    const classes = useStyles();

    return(
        <div className={classes.textField}>
            <TextField
                variant="outlined"
                margin="normal"
                fullWidth
                required={true}
                id="firstName"
                label="First Name"
                name="firstName"
                autoFocus
                onChange={props.onChange}
                value={props.info.firstName}
              />
              <TextField
                variant="outlined"
                margin="normal"
                fullWidth
                required
                name="lastName"
                label="Last Name"
                id="lastName"
                onChange={props.onChange}
                value={props.info.lastName}
              />
              <TextField
                variant="outlined"
                margin="normal"
                required
                fullWidth
                name="email"
                label="Email"
                id="email"
                onChange={props.onChange}
                value={props.info.email}
              />
        </div>
    )
}
Example #27
Source File: SurveyPage3.jsx    From Corona-tracker with MIT License 5 votes vote down vote up
SurveyPage3 = props => {
  const { setSurveyPage, surveyPage, setSurveyPage3, survey, setCompleted } = props;
  const { nonPhysical } = survey;
  const classes = useStyles();
  const [openComment, setOpenComment] = useState(nonPhysical.openComment || '');

  useEffect(() => {
    setSurveyPage3({ openComment });
    setCompleted(surveyPage);
  }, [openComment, setSurveyPage3, setCompleted, surveyPage]);

  const handleopenComment = value => {
    setOpenComment(value);
    setSurveyPage3({ openComment: value });
  };

  const goBack = () => {
    setSurveyPage(surveyPage - 1);
  };

  const submitButton = () => {
    setSurveyPage(surveyPage + 1);
  };

  return (
    <div className={classes.root}>
      <Grid container justify="center" spacing={1} className={classes.grid}>
        <Typography>
          <b>Q6: Anything other symptoms or comments you want to add?</b>
        </Typography>
        <Grid container justify="center" spacing={1} className={classes.grid}>
          <Grid item xs={12}>
            <TextField
              variant="outlined"
              placeholder="e.g. loss of smell or taste"
              className={classes.additionalComments}
              defaultValue={openComment}
              onChange={e => handleopenComment(e.target.value)}
            />
          </Grid>
          <Grid item xs={12}>
            <Button onClick={goBack} variant="outlined" color="secondary" className={classes.continueButton}>
              BACK
            </Button>
            <Button onClick={submitButton} color="secondary" className={classes.continueButton}>
              CONTINUE
            </Button>
          </Grid>
        </Grid>
      </Grid>
    </div>
  );
}
Example #28
Source File: Discussion.js    From app with MIT License 5 votes vote down vote up
function CommentEntry({ requestId }) {
  const firestore = useFirestore();
  const user = useUser();
  const { FieldValue } = useFirestore;
  const { showSuccess, showError } = useNotifications();

  const { register, handleSubmit, errors, reset, isSubmitting } = useForm({
    nativeValidation: false,
  });
  const [showForm, setShowForm] = useState(false);

  const userProfile = useFirestoreDoc(
    firestore.doc(`${USERS_COLLECTION}/${user.uid}`),
  );

  if (!showForm) {
    return (
      <Button onClick={() => setShowForm(true)} data-test="add-private-comment">
        Add Comment
      </Button>
    );
  }

  async function onSubmit(values) {
    const comment = {
      requestId,
      kind: 1, // Discussion
      createdBy: user.uid,
      createdAt: FieldValue.serverTimestamp(),
      author: {
        firstName: userProfile.get('firstName') || '',
        displayName: userProfile.get('displayName') || '',
      },
      contentType: 'text',
      content: values.comment,
    };
    try {
      await firestore.collection(REQUESTS_DISCUSSIONS_COLLECTION).add(comment);
      reset();
      setShowForm(false);
      showSuccess('Comment added');
    } catch (err) {
      // eslint-disable-next-line no-console
      console.log('Comment add error', err);
      showError('Unexpected error, failed to add comment.');
    }
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <TextField
        name="comment"
        multiline
        label="Comment"
        variant="outlined"
        fullWidth
        margin="dense"
        data-test="private-comment-input"
        error={!!errors.comment}
        helperText={errors.comment && 'Please enter a comment.'}
        inputRef={register({ required: true })}
      />
      <Button
        size="small"
        color="primary"
        variant="contained"
        type="submit"
        data-test="submit-private-comment"
        disabled={isSubmitting}>
        Add Comment
      </Button>
    </form>
  );
}
Example #29
Source File: Login.js    From Designer-Client with GNU General Public License v3.0 5 votes vote down vote up
function Login() {
  const classes = useStyles();
  const dispatch = useDispatch();
  
  const initialLoginForm = {
    username: "",
    password: ""
  }
  const [loginForm, setLoginForm] = useState(initialLoginForm);
  const loading = useSelector(state => state.users.loading);

  function handleChange(e) {
    const newForm = {
      ...loginForm,
      [e.target.name]: e.target.value
    }
    setLoginForm(newForm);
  }

  function handleSubmit(e) {
    e.preventDefault();
    dispatch(userActions.login(loginForm))
    .then((response) => {
      if(response.error) {
        alertActions.handleError(dispatch, response.error);
        return;
      }
      history.push("/");
    })
  }

  function onClickRegist(e) {
    history.push('/regist');
  }
  
  return (
    <Box className={classes.root}>
      <Card className={classes.loginCard}>
        <CardHeader
          title="로그인"
          subheader="API Designer"
        />
        <CardContent>
        <form className={classes.loginForm} noValidate autoComplete="off" onSubmit={handleSubmit}>
          <Container className={classes.loginContainer} maxWidth="lg">
            <TextField className={classes.input} autoComplete='false' id="usernameInput" label="Username" name="username" value={loginForm.username} onChange={handleChange}/>
            <TextField className={classes.input} autoComplete='false' id="passwordInput" label="Password" name="password" value={loginForm.password} onChange={handleChange} type="password"/>
          </Container>
          <Grid className={classes.buttonArea} container direction="column" justify="center" alignitem="center">
            <Grid item>
              {!loading &&
                <Button type="submit" className={classes.loginButton} variant="contained">로그인</Button>
              }
              {loading &&
                <Button disabled className={classes.loginButton} variant="contained">로그인중...</Button>
              }
            </Grid>
            <Grid item>
              <Button variant="text" type="button" onClick={onClickRegist}>회원가입</Button>  
            </Grid>
          </Grid>
        </form>
        </CardContent>
      </Card>
    </Box>
  );
}