I’ve previously asked a question regarding the passing of state for react through props here: Laggy TextField Updates in React.
I’ve decided to refactor my code using ChrisG’s method, where I store states in the parent FormSection, and pass props into the child CompanyField.
Parent:
class FormSection extends React.Component {
state = {
company: '',
jobType: ''
};
createHandleChange(name) {
return (e) => {
try {
this.setState({ [name]: e.target.value.toLowerCase() }); //convert to lowercase if text data
} catch {
this.setState({ [name]: e.target.value });
}
console.log(name, e.target.value);
};
}
render() {
return (
<FormContainer>
<CompanyField # Working Correctly
value={this.state.company}
handleChange={this.createHandleChange("company")}
/>
<JobTypeField # Does not work
value={this.state.jobType}
handleChange={this.createHandleChange("jobType")}
/>
</FormContainer>
)
}
TextFieldStyled is just MUI’s textfield that was styled using styled components.
Child:
class CompanyField extends React.Component {
render() {
return (
<TextFieldStyled
id = "outlined-basic"
label = "Company"
variant = "outlined"
fullWidth
value={this.props.value}
onChange={this.props.handleChange}
/>
);
}
}
This managed to successfully update the parent components state. However, when doing the same thing to MUI’s autocomplete:
class JobTypeField extends React.Component {
render() {
return (
<DropDownStyled>
<Autocomplete
disablePortal
id="combo-box-demo"
options={jobType}
value={this.props.value}
onChange={this.props.handleChange}
renderInput={(params) => <TextField {...params} label="Job Type" />}
/>
</DropDownStyled>
);
}
}
const jobType = [
{ label: 'Full-Time' },
{ label: 'Part-Time' },
{ label: 'Internship' },
{ label: 'Contract' },
{ label: 'Freelance' },
];
This error occurs:
The value provided to Autocomplete is invalid.
None of the options match with 0
.
You can use the isOptionEqualToValue
prop to customize the equality test.
After clicking an option, it defaults to 0.
Additionally, the state is not updated.
Thanks!