#Combobox with mantine form
10 messages · Page 1 of 1 (latest)
Hello, I would like to ask if there's anyone who can provide an example on integrating Mantine forms to the Combobox with Custom Options? I'm following the example here: https://mantine.dev...
to add to above i'd recommend using useUncontrolled for your generic combobox component, this way you can add value + onChange as optional props to your component
https://mantine.dev/hooks/use-uncontrolled/
it makes it really easy to pass state/uncontrolled props into the component
Fun fact: i was able to come to using this hook by myself, even though didn't know about it existance. Was looking through MultiSelect source code - and understood its purpose. But i have problem with types of setValue inside handleValueSelect/handleValueRemove: https://codesandbox.io/p/sandbox/elastic-silence-gc7sqt. How can i fix it?
you can't use a callback function in the setValue, it has to be a value
so you can get the current value above instead like this
const current = [..._value];
Like this?
const handleValueSelect = (val: string) => {
const value = _value.includes(val)
? _value.filter((v) => v !== val)
: [..._value, val];
setValue(value);
};
potentially, best practice is to make a copy of the state before doing any modifications/calling any methods on it
- may you provide example of mentioned best practice? i'm not very experienced dev;
- why i can't use setState callback to get current state value? is it use-unControlled flaw or by design?
Thank you in advance for helping.
- may you provide example of mentioned best practice? i'm not very experienced dev;
in react, state is immutable & frozen. you cannot change the values easy with the=symbol
const [state, setState] = useState(0);
state = 1; // will not work properly
generally, when you want to work with an existing state, if you are going to modify it in anyway, it's worth making a direct copy of it. this copy is separate from the state, so if you want to re-assign it, like with filter, it will work without problems, you can then just take that copy and assign it to the setter
it's also a very common pattern: you'll see in a lot of github code where people make a copy, then do some work to it. whereas reading the ternary, it takes a second to understand what is happening as an outside dev. but as an outside dev, if you see a copy happening, you immediately know that the other developer is planning to do some changes to a copy of a state. it becomes much quicker to read this way
- why i can't use setState callback to get current state value? is it use-unControlled flaw or by design?
limitation of useControlled, it has not been given the same feature as the normal react state handler