I’m working on a reactjs project where I use material ui in order to create my components. I have a form to create an event in my project and there I have used the Autocomplete
component. When there is change occur in that filed , I wanted to update the state of that filed.
Here is the code:
export default function AddEvent() {
let navigate=useNavigate();
const [event, setEvent]=useState({
eventName:'',
eventType:'',
eventLocationType:'',
location:'',
startTime:null,
endTime:null
})
const {eventName,eventType,eventLocationType,location,startTime,endTime}=event;
const onInputChange = (e)=>{
if (e && e.target && e.target.name){
setEvent({...event,[e.target.name]:e.target.value})
}
}
const onSubmit =async (e)=>{
e.preventDefault();
console.log(event)
await axios.post('http://localhost:8080/api/event/saveEvent',event);
navigate('/');
}
return (
...
<FormLabel disabled={true} align="left">
Event Location
</FormLabel>
<Autocomplete
freeSolo
name="location"
value={location}
onChange={(e)=>onInputChange(e)}
options={locations}
renderInput={(params) => (
<TextField
{...params}
label="Location"
variant="outlined"
margin="normal"
fullWidth
sx={{ paddingBottom: "10px" }}
/>
)}
/>
)
Here the onChange
is not triggered when changing the location field.
Can someone please help me with this issue? Thank you in advance!
3
Answers
try this way:
The
onChange
event in theAutocomplete
expects two arguments: the first one is the event object, and the second one is the value.To fix the issue, you can modify the onChange event handler in your Autocomplete component like this:
In addition changing the
onInputChange
function to make use the second parameter as explained by @AbhishekGarg’s and @rMonteiro’s answers, and making sure you pass the second parameter through toonInputChange
as noted by @AbhishekGarg’s comment, it looks like you might also need to change theonChange
attribute of the Autocomplete component toonInputChange
(possibly depending on what exactly you’re trying to achieve).