skip to Main Content

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


  1. try this way:

    setEvent(prevEvent => ({...prevEvent,[e.target.name]:e.target.value}))
    
    Login or Signup to reply.
  2. The onChange event in the Autocomplete 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:

    
    const onInputChange = (e, newValue)=>{
        if (e && e.target && e.target.name){
        setEvent({...event,[e.target.name]:newValue})
        }
      }
    
    <Autocomplete
      freeSolo
      name="location"
      value={location}
      onChange={onInputChange}
      options={locations}
      renderInput={(params) => (
        <TextField
          {...params}
          label="Location"
          variant="outlined"
          margin="normal"
          fullWidth
          sx={{ paddingBottom: "10px" }}
        />
      )}
    />
    
    Login or Signup to reply.
  3. 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 to onInputChange as noted by @AbhishekGarg’s comment, it looks like you might also need to change the onChange attribute of the Autocomplete component to onInputChange (possibly depending on what exactly you’re trying to achieve).

    const { Autocomplete, TextField } = MaterialUI;
    
    const locations = ['Mexico', 'India', 'Egypt'];
    
    function AddEvent() {
      const [event, setEvent] = React.useState({
        eventName:'',
        eventType:'',
        eventLocationType:'',
        location:'',
        startTime:null,
        endTime:null
      })
    
      const {eventName,eventType,eventLocationType,location,startTime,endTime}=event;
    
      const onInputChange = (e, value) => {
        setEvent({...event, location: value})
      }
      
      console.log('location:', location);
    
      return (
        <Autocomplete
          freeSolo
          name="location"
          value={location}
          onInputChange={onInputChange}
          options={locations}
          renderInput={(params) => (
            <TextField
              {...params}
              label="Location"
              variant="outlined"
              margin="normal"
              fullWidth
              sx={{ paddingBottom: "10px" }}
            />
          )}
        />
      )
    }
    
    const root = ReactDOM.createRoot(document.getElementById('app'));
    root.render(<AddEvent />);
    .as-console-wrapper {
      max-height: 90px !important;
    }
    <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
    <script crossorigin src="https://unpkg.com/@mui/material@latest/umd/material-ui.production.min.js"></script>
    
    <div id="app"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search