Reputation: 215
I am using react with Material UI and typescript and have a form. On form submission if inputs have validation error i would like to scroll to the first input with the validation error. I have pasted the simple form code below which inject validation error in the town input on submission. In reality error could be in any or multiple inputs.
import React, { useState, FormEvent } from 'react';
import { Grid, TextField, Button } from '@material-ui/core';
const ScrollTest = () => {
const [state, setState] = useState<{ town: string; county: string }>({
town: '',
county: '',
});
const [error, setError] = useState({ town: '', county: '' });
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { name, value } = e.target;
const errorVal = !value ? `${name} is requied` : '';
setState({ ...state, [name]: value });
setError({ ...error, [name]: errorVal });
};
const handleSubmit = (e: FormEvent) => {
e.preventDefault();
if (!state.town) {
setError({ ...error, town: 'Town input is required' });
}
};
return (
<>
<form onSubmit={(e) => handleSubmit(e)} noValidate>
<Grid container justify='center' alignItems='center' spacing={2}>
<Grid item xs={12} md={6}>
<TextField
error={!!error.town}
variant='outlined'
fullWidth
id='town'
label='Town'
name='town'
autoComplete='town'
placeholder='Town *'
value={state.town || ''}
onChange={handleChange}
helperText={error.town}
/>
</Grid>
</Grid>
<Grid container justify='center' alignItems='center' spacing={2}>
<Grid item xs={12} md={6}>
<TextField
error={!!error.county}
variant='outlined'
fullWidth
id='county'
label='County'
name='county'
autoComplete='county'
placeholder='County'
value={state.county || ''}
onChange={handleChange}
helperText={error.county}
/>
</Grid>
</Grid>
<Grid container justify='center' alignItems='center' spacing={2}>
<Grid item xs={12} md={6}>
<TextField
variant='outlined'
fullWidth
id='county2'
label='County2'
name='county2'
autoComplete='county2'
placeholder='County2'
value={state.county || ''}
onChange={handleChange}
/>
</Grid>
</Grid>
<br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br>{' '}
<br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br>{' '}
<br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br>{' '}
<br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br>{' '}
<br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br> <br></br>{' '}
<br></br> <br></br> <br></br>
<Grid container justify='center' alignItems='center'>
<Grid item xs={12} md={6}>
<Button type='submit' fullWidth variant='contained' color='primary'>
Update profile
</Button>
</Grid>
</Grid>
</form>
</>
);
};
export default ScrollTest;
Any idea how to scroll to the first input with the validation error.
Upvotes: 4
Views: 18200
Reputation: 427
Another way to do this easily is by using React Hook Form
And utilize shouldFocusError
option when initializing useForm
hook
For example:
const { register, handleSubmit } = useForm({ shouldFocusError: true })
Upvotes: 1
Reputation: 148
<Button
disabled={isSubmitting}
variant="contained"
color="primary"
onClick={() => {
const err = Object.keys(errors);
if (err.length) {
const input = document.querySelector(
`input[name=${err[0]}]`
);
input.scrollIntoView({
behavior: 'smooth',
block: 'center',
inline: 'start',
});
}
submitForm();
}}
>
{isSubmitting ? (
<CircularProgress size={22} />
) : (
'Submit'
)}
</Button>
This is the easiest thing you can do to scroll into the first error in a big form using Formik, I did this inside Formik submit button, where errors
object and submitForm()
function comes from Formik
Upvotes: 7
Reputation: 878
I think you can save the reference of the input where you are getting error and you can scroll to that reference, you can refer this I think
Upvotes: 0