hc-oss / react-tag-input-component

lightweight react component for tag(s) input
https://codesandbox.io/s/react-tag-input-component-rgf97
MIT License
82 stars 36 forks source link

Value not being set when form opened #19

Closed decarlomw closed 2 years ago

decarlomw commented 2 years ago

I'm setting the input to a default value inside useEffect, but the value is not being set inside TagsInput.

const [allergyTags,setAllergyTags] = useState([]);

useEffect(() => {
setAllergyTags(["test1", "test2"]);

}
   <TagsInput
                        onChange={setAllergyTags}
                        value={allergyTags}
                        name="allergy"
                        placeHolder="enter allergies"
                      />

I'm expecting the value to be test1, test2. if I add allergyTags to the placeholder, it shows the correct information. Any help would be greatly appreciated.

codesandbox

harshzalavadiya commented 2 years ago

@decarlomw Best way to do this will be to pre-populate value in useState itself like below

const [allergyTags,setAllergyTags] = useState(["test1", "test2"]);

<TagsInput
    onChange={setAllergyTags}
    value={allergyTags}
    name="allergy"
    placeHolder="enter allergies"
  />

but if that's not what you are looking for then since this component is uncontrolled you can force re-initialize component when setting values from outside like below as well

export default function App() {
  const [allergyTags, setAllergyTags] = useState([]);
  const [k, setK] = useState();

  useEffect(() => {
    setAllergyTags(["test1", "test2"]);
    setK(new Date().getTime());
  }, []);

  return (
    <TagsInput
      onChange={setAllergyTags}
      value={allergyTags}
      name="allergy"
      key={k}
      placeHolder="enter allergies"
    />
  );
}

Sandbox link here https://codesandbox.io/s/clever-platform-yye8m8?file=/src/App.js

harshzalavadiya commented 2 years ago

Related to https://github.com/hc-oss/react-tag-input-component/issues/19

decarlomw commented 2 years ago

Thanks, the second portion was what I was looking for!