In many times we need to customize the input fields in the forms of our application. While we talk about javascript frameworks then now a days there are so many npm packages available which make the customization task easy for the developers.
In this article today, I will explain you to customize the dropdown input field in react.js application. For the required task we will use react-select npm package here.
npx create-react-app dropdown-example
Once above command run successfully, move to the React.js project folder.
npm install --save react-select
import npm library in App.js and update the file for achieving the task. Open the App.js file and put the below code in it.
In the above file, At the top we have imported the need libraries. Below that we have created static list of city to show the city list in dropdown input field. And at below we have binded the data with html.
With the current npm library we have used above, We can use many other customizations. Have a look below the other options available with this npm package.
autoFocus
- focus the control when it mountsclassName
- apply a className to the controlclassNamePrefix
- apply classNames to inner elements with the given prefixisDisabled
- disable the controlisMulti
- allow the user to select multiple valuesisSearchable
- allow the user to search for matching optionsname
- generate an HTML input with this name, containing the current valueonChange
- subscribe to change eventsoptions
- specify the options the user can select fromplaceholder
- change the text displayed when no option is selectedvalue
- control the current value
We can control the following props by providing values for them.
value
/ onChange
- specify the current value of the controlmenuIsOpen
/ onMenuOpen
/ onMenuClose
- control whether the menu is openinputValue
/ onInputChange
- control the value of the search input (changing this will update the available options)If you don't provide these props, you can set the initial value of the state they control:
defaultValue
- set the initial value of the controldefaultMenuIsOpen
- set the initial open value of the menudefaultInputValue
- set the initial value of the search input
React-select npm package also exposes two public methods:
focus()
- focus the control programmaticallyblur()
- blur the control programmatically
So in this demo, We learned to customize the dropdown field in React.js application. You can find other react.js sample projects here.
That’s all for now. Thank you for reading and I hope this demo will be very helpful to customize the dropdown field in React.js application.
Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.