@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: AddUpdateForm.js From to-view-list with MIT License | 4 votes |
AddUpdateForm = () => {
const [entry, setEntry] = useState(initialInputValues);
const [tagInput, setTagInput] = useState('');
const [error, setError] = useState('');
const [{ editValues, isLoading }, dispatch] = useEntryContext();
const history = useHistory();
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down('xs'));
const classes = useFormStyles();
useEffect(() => {
if (editValues) {
setEntry(editValues);
}
}, [editValues]);
const { title, link, description, type, tags } = entry;
const handleOnChange = (e) => {
setEntry({
...entry,
[e.target.name]: e.target.value,
});
};
const handleTagButton = () => {
if (tagInput === '') return;
if (tags.includes(tagInput)) {
return setError(`Tags need to be unique. Two tags can't be same.`);
}
setEntry({ ...entry, tags: tags.concat(tagInput.toLowerCase()) });
setTagInput('');
};
const handleTagDelete = (targetTag) => {
setEntry({ ...entry, tags: tags.filter((t) => t !== targetTag) });
};
const handleClearInput = () => {
if (editValues) {
dispatch(resetEditValues());
}
setEntry(initialInputValues);
setTagInput('');
};
const handleSubmit = async (e) => {
e.preventDefault();
if (tags.length === 0) {
return setError('Atleast one tag is required.');
}
try {
dispatch(toggleIsLoading());
if (editValues) {
const entryRes = await entryService.update(editValues.id, entry);
dispatch(updateEntry(entryRes));
notify(
dispatch,
`Entry "${editValues.title}" has been successfully updated.`,
'success'
);
dispatch(resetEditValues());
} else {
const entryRes = await entryService.create(entry);
dispatch(addEntry(entryRes));
notify(
dispatch,
`New entry "${entryRes.title}" has been successfully added!`,
'success'
);
}
dispatch(toggleIsLoading());
setEntry(initialInputValues);
setTagInput('');
history.push('/');
} catch (err) {
dispatch(toggleIsLoading());
const errRes = err?.response?.data;
if (
errRes?.error.includes('title') &&
errRes?.error.includes('allowed length (40)')
) {
return setError(`Title field's maximum character limit is 40. `);
} else if (
errRes?.error.includes('description') &&
errRes?.error.includes('allowed length (250)')
) {
return setError(`Description field's maximum character limit is 250. `);
} else if (errRes?.error) {
return setError(errRes.error);
} else {
return setError(err.message);
}
}
};
return (
<Paper>
<form onSubmit={handleSubmit} className={classes.root}>
<Typography
variant={isMobile ? 'h5' : 'h4'}
color="primary"
className={classes.formTitle}
>
{editValues ? 'Update the entry' : 'Add a new entry'}
</Typography>
<div className={classes.input}>
<TitleIcon color="secondary" className={classes.inputIcon} />
<TextField
color="secondary"
required
label="Title"
value={title}
name="title"
onChange={handleOnChange}
fullWidth
/>
</div>
<div className={classes.input}>
<LinkIcon color="secondary" className={classes.inputIcon} />
<TextField
color="secondary"
required
label="Link"
value={link}
name="link"
onChange={handleOnChange}
fullWidth
/>
</div>
<div className={classes.input}>
<DescriptionIcon color="secondary" className={classes.inputIcon} />
<TextField
color="secondary"
required
multiline
label="Description"
value={description}
name="description"
onChange={handleOnChange}
fullWidth
/>
</div>
<div className={classes.tagArea}>
<div className={classes.input}>
<LocalOfferIcon color="secondary" className={classes.inputIcon} />
<TextField
color="secondary"
label="Add Tags"
value={tagInput}
onChange={({ target }) => setTagInput(target.value)}
/>
<Button
color="primary"
size="small"
variant="outlined"
onClick={handleTagButton}
className={classes.tagButton}
>
Add
</Button>
</div>
<div className={classes.tagGroup}>
{tags.map((tag) => (
<Chip
key={tag}
label={tag}
onDelete={() => handleTagDelete(tag)}
variant="outlined"
color="secondary"
className={classes.tag}
/>
))}
</div>
</div>
<div className={classes.radioInput}>
<CheckCircleOutlineIcon color="secondary" />
<FormLabel component="legend" className={classes.radioLabel}>
Link Type:
</FormLabel>
<RadioGroup
row
label="Type"
value={type}
name="type"
onChange={handleOnChange}
className={classes.radioGroup}
>
<FormControlLabel
label="Article"
control={<Radio color="secondary" />}
value="article"
checked={type === 'article'}
/>
<FormControlLabel
label="Video"
control={<Radio color="secondary" />}
value="video"
checked={type === 'video'}
/>
<FormControlLabel
label="Other"
control={<Radio color="secondary" />}
value="other"
checked={type === 'other'}
/>
</RadioGroup>
</div>
<div className={classes.buttonGroup}>
<Button
variant="outlined"
color="primary"
size={isMobile ? 'medium' : 'large'}
startIcon={<BackspaceIcon />}
onClick={handleClearInput}
>
Clear
</Button>
<Button
type="submit"
variant="contained"
color="primary"
size={isMobile ? 'medium' : 'large'}
startIcon={editValues ? <EditIcon /> : <PostAddIcon />}
disabled={isLoading}
>
{editValues
? isLoading
? 'Updating Entry'
: 'Update Entry'
: isLoading
? 'Adding Entry'
: 'Add Entry'}
</Button>
</div>
{error && (
<AlertBox
message={error}
severity="error"
clearError={() => setError(null)}
/>
)}
</form>
</Paper>
);
}
Example #2
Source File: LoginForm.js From to-view-list with MIT License | 4 votes |
LoginForm = () => {
const [credentials, setCredentials] = useState({
email: '',
password: '',
});
const [error, setError] = useState(null);
const [showPass, setShowPass] = useState(false);
const [, authDispatch] = useAuthContext();
const [{ isLoading }, entryDispatch] = useEntryContext();
const classes = useRegisterLoginForm();
const history = useHistory();
const { email, password } = credentials;
const handleOnChange = (e) => {
setCredentials({ ...credentials, [e.target.name]: e.target.value });
};
const handleLogin = async (e) => {
e.preventDefault();
try {
entryDispatch(toggleIsLoading());
const user = await authService.login(credentials);
entryService.setToken(user.token);
authDispatch(loginUser(user));
storageService.saveUser(user);
entryDispatch(toggleIsLoading());
setCredentials({
email: '',
password: '',
});
setError(null);
history.push('/');
notify(
entryDispatch,
`Welcome, ${user.displayName}! You're logged in.`,
'success'
);
} catch (err) {
entryDispatch(toggleIsLoading());
if (err?.response?.data?.error) {
setError({ message: err.response.data.error, severity: 'error' });
} else {
setError({ message: err.message, severity: 'error' });
}
}
};
return (
<Paper className={classes.root}>
<form onSubmit={handleLogin} className={classes.form}>
<Typography variant="h4" color="primary" className={classes.formTitle}>
Login to your account
</Typography>
<div className={classes.input}>
<AlternateEmailIcon color="secondary" className={classes.inputIcon} />
<TextField
color="secondary"
required
type="email"
label="Email"
value={email}
name="email"
onChange={handleOnChange}
fullWidth
/>
</div>
<div className={classes.input}>
<LockIcon color="secondary" className={classes.inputIcon} />
<TextField
color="secondary"
required
type={showPass ? 'text' : 'password'}
label="Password"
value={password}
name="password"
onChange={handleOnChange}
fullWidth
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton onClick={() => setShowPass(!showPass)}>
{showPass ? <VisibilityOffIcon /> : <VisibilityIcon />}
</IconButton>
</InputAdornment>
),
}}
/>
</div>
<Button
type="submit"
variant="contained"
color="primary"
size="large"
className={classes.submitButton}
startIcon={<ExitToAppIcon />}
disabled={isLoading}
>
{isLoading ? 'Logging in' : 'Login'}
</Button>
<Typography variant="body1" className={classes.bottomText}>
Don't have an account?{' '}
<Link component={RouterLink} to="/register">
Register.
</Link>
</Typography>
{error && (
<AlertBox
message={error.message}
severity={error.severity}
clearError={() => setError(null)}
title={error.title}
/>
)}
<DemoCredsBox />
</form>
</Paper>
);
}
Example #3
Source File: RegisterForm.js From to-view-list with MIT License | 4 votes |
RegisterForm = () => {
const [userDetails, setUserDetails] = useState({
displayName: '',
email: '',
password: '',
});
const [confirmPassword, setConfirmPassword] = useState('');
const [error, setError] = useState(null);
const [showPass, setShowPass] = useState(false);
const [showConfirmPass, setShowConfirmPass] = useState(false);
const [, authDispatch] = useAuthContext();
const [{ isLoading }, entryDispatch] = useEntryContext();
const classes = useRegisterLoginForm();
const history = useHistory();
const { displayName, email, password } = userDetails;
const handleOnChange = (e) => {
setUserDetails({ ...userDetails, [e.target.name]: e.target.value });
};
const handleRegister = async (e) => {
e.preventDefault();
if (password !== confirmPassword) {
return setError(`Confirm password failed! Both passwords need to match.`);
}
try {
entryDispatch(toggleIsLoading());
const user = await authService.register(userDetails);
entryService.setToken(user.token);
authDispatch(registerUser(user));
storageService.saveUser(user);
entryDispatch(toggleIsLoading());
setUserDetails({
displayName: '',
email: '',
password: '',
});
setConfirmPassword('');
setError(null);
history.push('/');
notify(
entryDispatch,
`Welcome, ${user.displayName}! Your account has been registered.`,
'success'
);
} catch (err) {
entryDispatch(toggleIsLoading());
if (err?.response?.data?.error) {
setError(err.response.data.error);
} else {
setError(err.message);
}
}
};
return (
<Paper className={classes.root}>
<form onSubmit={handleRegister} className={classes.form}>
<Typography variant="h4" color="primary" className={classes.formTitle}>
Create an account
</Typography>
<div className={classes.input}>
<PersonIcon color="secondary" className={classes.inputIcon} />
<TextField
color="secondary"
required
label="Display Name"
value={displayName}
name="displayName"
onChange={handleOnChange}
fullWidth
/>
</div>
<div className={classes.input}>
<AlternateEmailIcon color="secondary" className={classes.inputIcon} />
<TextField
color="secondary"
required
type="email"
label="Email"
value={email}
name="email"
onChange={handleOnChange}
fullWidth
/>
</div>
<div className={classes.input}>
<LockIcon color="secondary" className={classes.inputIcon} />
<TextField
color="secondary"
required
type={showPass ? 'text' : 'password'}
label="Password"
value={password}
name="password"
onChange={handleOnChange}
fullWidth
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton onClick={() => setShowPass(!showPass)}>
{showPass ? <VisibilityOffIcon /> : <VisibilityIcon />}
</IconButton>
</InputAdornment>
),
}}
/>
</div>
<div className={classes.input}>
<EnhancedEncryptionIcon
color="secondary"
className={classes.inputIcon}
/>
<TextField
color="secondary"
required
type={showConfirmPass ? 'text' : 'password'}
label="Confirm Password"
value={confirmPassword}
name="confirmPassword"
onChange={({ target }) => setConfirmPassword(target.value)}
fullWidth
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton
onClick={() => setShowConfirmPass(!showConfirmPass)}
>
{showConfirmPass ? (
<VisibilityOffIcon />
) : (
<VisibilityIcon />
)}
</IconButton>
</InputAdornment>
),
}}
/>
</div>
<Button
type="submit"
variant="contained"
color="primary"
size="large"
className={classes.submitButton}
startIcon={<PersonAddIcon />}
disabled={isLoading}
>
{isLoading ? 'Registering' : 'Register'}
</Button>
<Typography variant="body1" className={classes.bottomText}>
Already have an account?{' '}
<Link component={RouterLink} to="/login">
Login.
</Link>
</Typography>
{error && (
<AlertBox
message={error}
severity="error"
clearError={() => setError(null)}
/>
)}
<DemoCredsBox />
</form>
</Paper>
);
}
Example #4
Source File: UploadForm.js From youtube-clone with MIT License | 4 votes |
UploadForm = ({ type, onSubmit, formRef }) => {
const classes = useStyles();
const form = (type) => {
let validation = {};
let initialValues = {};
if (["details"].includes(type)) {
initialValues = {
title: "",
description: "",
category: 0,
};
validation = {
title: Yup.string().required("Title is required"),
description: Yup.string()
.max(100, "Max characters is 100")
.required("Description is required"),
category: Yup.number().required("Category is required"),
};
}
if (["visibility"].includes(type)) {
initialValues.visibility = "0";
validation.visibility = Yup.string().required("Visibility is required");
}
return { validationSchema: Yup.object().shape(validation), initialValues };
};
const validationSchema = form(type).validationSchema;
const initialValues = form(type).initialValues;
return (
<Formik
innerRef={formRef}
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={(values) => {
onSubmit(values);
}}
validateOnMount
>
{({ values, errors, touched, handleChange, handleBlur }) => (
<>
{type === "details" && (
<>
<TextField
error={touched.title && errors.title}
id="details-title"
label="title"
name="title"
value={values.title}
helperText={errors.title}
variant="outlined"
onChange={handleChange}
onBlur={handleBlur}
className={classes.spacing}
/>
<TextField
error={touched.description && errors.description}
id="details-description"
label="description"
name="description"
value={values.description}
helperText={errors.description}
variant="outlined"
onChange={handleChange}
className={classes.spacing}
onBlur={handleBlur}
/>
<Select
id="category"
label="category"
name="category"
value={values.category}
className={classes.spacing}
onChange={handleChange}
onBlur={handleBlur}
>
{categories.map((value, index) => (
<MenuItem key={index} value={index}>
{capitalize(value)}
</MenuItem>
))}
</Select>
{errors.category && touched.color && (
<FormHelperText>{errors.category}</FormHelperText>
)}
</>
)}
{type === "visibility" && (
<>
<FormControl
component="fieldset"
error={errors.visibility}
className={classes.formControl}
>
<FormLabel component="legend">
Pick the visibility of this video:
</FormLabel>
<RadioGroup
aria-label="visibility"
name="visibility"
value={values.visibility}
onChange={handleChange}
>
{visibility.map((value, index) => (
<FormControlLabel
key={index}
value={index + ""}
control={<Radio />}
label={capitalize(value)}
/>
))}
</RadioGroup>
{errors.visibility && touched.color && (
<FormHelperText>{errors.visibility}</FormHelperText>
)}{" "}
</FormControl>
</>
)}
</>
)}
</Formik>
);
}