Handle change on Autocomplete Component from material ui

前端 未结 5 974
無奈伤痛
無奈伤痛 2021-02-01 17:36

I want to use Autocomplete component for input tags. I\'m trying to get the tags and save them on a state so I can later save them on the database. I\'m using funct

5条回答
  •  南旧
    南旧 (楼主)
    2021-02-01 18:19

    I wanted to update my state when I select an option from the autocomplete. I had a global onChange handler that manages for all inputs

             const {name, value } = event.target;
             setTukio({
              ...tukio,
              [name]: value,
            });
    

    That updates the object dynamically based on the name of the field. But on the Autocomplete the name returns blank. So I changed the handler from onChange to onSelect. Then either create a separate function to handle the change or as in my case added an if statement to check if the name is not passed.

    // This one will set state for my onSelect handler of the autocomplete 
         if (!name) {
          setTukio({
            ...tukio,
            tags: value,
          });
         } else {
          setTukio({
            ...tukio,
            [name]: value,
          });
        }
    

    The above approach works if u have a single autocomplete. If you have multiple u can pass a custom function like below

     option.tagName}
        id="tags"
        name="tags"
        autoComplete
        includeInputInList
        onSelect={(event) => handleTag(event, 'tags')}
              renderInput={(params) => }
            />
    
    // The handler 
    const handleTag = ({ target }, fieldName) => {
        const { value } = target;
        switch (fieldName) {
          case 'tags':
            console.log('Value ',  value)
            // Do your stuff here
            break;
          default:
        }
      };
    

提交回复
热议问题