How to add styles to autocomplete in ReactJS ?
Autocomplete Component is used for auto-completing the text value with the option value. It basically allows the user to type and select the item from a list of suggestions. It improves the user experience by giving suggestions while the user type.
In this article, you will examine how to style an Autocomplete component in ReactJS.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install --save react-autocomplete
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Following code has Autocomplete Component with styling added.
- On the Autocomplete element, className doesn’t apply to the text input as you might expect. You can’t use the className on the autocomplete component, you have to use the inputProps property.
- The inputProps is commonly used for (but not limited to) placeholder, event handlers (onFocus, onBlur, etc.), autoFocus, etc.
- You can customize the styles in inputProps in the above code.
- In the renderItem prop, you can add style as a set of styles that can be applied to improve the look of the items in the dropdown menu.
Step to Run Application: Run the application using the following command from the root directory of the project:
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: