4
4
4ch232020-11-29 00:24:16
React
4ch23, 2020-11-29 00:24:16

How to pass only value to the "value" prop of the Material-ui Autocomplete component?

I constantly encounter the same problem, when plugins for working with drop-down lists (comboboxes) accept not a specific value, but a {label, value} object in the "value" and "defaultValue" props. Maybe I'm missing something and do it "correctly", but I'm preparing the backing incorrectly? If, nevertheless, my expectations are logical, please suggest npm wrapper packages over Material-UI that can handle both options.

Example: A user object comes from the back

{id: 1, role_id: 2, name: "user"} (Допустим role_id=2 это "admin")

So in order for the page to display "admin" you need to write like this:
<Autocomplete value={{label: "admin", value: 2}} options=[{label: "superadmin", value: 1}, {label: "admin", value: 2}] />


And I would like:
<Autocomplete value={2} options=[{label: "superadmin", value: 1}, {label: "admin", value: 2}] />


ps writing one wrapper for a component is not a problem, but there are a lot of third-party libraries that work with exactly the Autocomplete option that is in the material, for example, the same React-final-form. Here I would rather get an understanding of why label passing is mandatory.
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Gimir, 2020-11-30
@Gimir

Well, so it works, so what's the difficulty then? This is how the component gets information from options. If the library does not provide the ability to override the default behavior (as in react-autocomplete, for example, where you need to write each action manually for your data, such as getOptions, getOptionFromOptions, etc.), then leave it as it is.
If you need a wrapper to control the select, you can use react-hook-form as an option , it has a Controller component that allows you to wrap the select from MaterialUI, plus there will be fewer renders.
Or make a controlled select.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question