Hi guys I have used material UI and react to create a form. I would like to use the focus property on a particular ref. Please find below the code for reference :-
Using createRef for initialising the reference.Following is the code for the constructor:-
constructor(props) {
super(props);
this.state = {
gender: '',
empType: '',
firstName: '',
lastName: '',
email: '',
officePincode: '',
dob: '',
mobile: '',
monthlySalary: '',
residentialPincode: '',
panNumber: ''
};
this.firstNameRef = React.createRef();
this.lastNameRef = React.createRef();
this.dobRef = React.createRef();
this.emailRef = React.createRef();
this.monthlySalaryRef = React.createRef();
this.officePincodeRef = React.createRef();
this.residentialPincodeRef = React.createRef();
this.panNumberRef = React.createRef();
}
I am using this array in the render method:-
const focusArray = [
this.firstNameRef,
this.lastNameRef,
this.dobRef,
this.emailRef,
this.monthlySalaryRef,
this.officePincodeRef,
this.residentialPincodeRef,
this.panNumberRef
];
// eslint-disable-next-line no-plusplus
for (let index = 0; index < focusArray.length; index++) {
const currentRef = focusArray[index];
if (currentRef.current) {
if (currentRef.current.value === '') {
currentRef.current.focus();
break;
}
}
}
Please find below code for the text field:-
<TextField
id="firstName"
name="firstName"
ref={this.firstNameRef}
value={firstName}
disabled={
firstName && disableNameField.has(params.get('utm_source'))
}
label="First Name"
error={formSubmitted && !validateName(firstName)}
onChange={this.handleChange()}
variant="outlined"
margin="normal"
helperText={
formSubmitted && !validateName(firstName)
? '*Please enter first name'
: ''
}
className={classes.input_field}
InputLabelProps={{
classes: {
root: classes.cssLabel,
focused: classes.cssFocused
}
}}
InputProps={{
classes: {
root: classes.cssOutlinedInput,
focused: classes.cssFocused,
notchedOutline: firstName
? classes.noOutline
: classes.notchedOutline
}
}}
/>
I am using a class based react component. Any help or suggestion is appreciated.