Wednesday, July 3, 2024
HomeLanguagesReactHow to add styles to autocomplete in ReactJS ?

How to add styles to autocomplete in ReactJS ?

Autocomplete functionality is widely used in web applications to provide users with suggestions or predictions as they type into input fields. ReactJS, a popular JavaScript library, offers various autocomplete packages that can be customized and styled to match the look and feel of your application. In this article, we will explore how to add styles to an autocomplete component in ReactJS using the Material-UI Autocomplete package.

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:

cd foldername

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.

Project Structure

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.

Javascript




import React, { useState } from 'react'
import Autocomplete from 'react-autocomplete'
 
function App() {
 
    // Defining a state named value, which
    // we can update by calling setValue
    // Value will store the typed value or
    // selected suggestion by the user
    const [value, setValue] = useState('');
 
    return (
        <div style={{
            display: 'flex', flexDirection: 'column',
            alignItems: 'center'
        }}>
            <div>
                {/* Inline css*/}
                <h4 style={{
                    padding: '15px',
                    border: '13px solid #b4f0b4',
                    color: 'rgb(11, 167, 11)'
                }}>
                    Geeks for Geeks : React
                    Autocomplete Component Styling
                </h4>
            </div>
            <div>
                <Autocomplete
 
                    // Items is the list of suggestions
                    // displayed while the user type
                    items={[
                        { label: 'C++' },
                        { label: 'C' },
                        { label: 'Python' },
                        { label: 'JavaScript' },
                        { label: 'Julia' },
                        { label: 'Java' },
                        { label: 'Objective C' },
                        { label: 'C#' },
                        { label: 'Dart' },
                        { label: 'Perl' }
                    ]}
 
                    // To handle the case that when
                    // the user type, suggested
                    // values should be independent
                    // of upper or lower case
                    shouldItemRender={(item, value
                    ) => item.label.toLowerCase()
                        .indexOf(value.toLowerCase()) > -1}
                    getItemValue={item => item.label}
                    renderItem={(item, isHighlighted) =>
                        // Styling to highlight selected item
                        <div style={{
                            background: isHighlighted ?
                                '#bcf5bc' : 'white'
                        }}
                            key={item.id}>
                            {item.label}
                        </div>
                    }
                    value={value}
 
                    // The onChange event watches for
                    // changes in an input field
                    onChange={e => setValue(e.target.value)}
 
                    // To set the state variable to value
                    // selected from dropdown
                    onSelect={(val) => setValue(val)}
 
                    // Added style in Autocomplete component
                    inputProps={{
                        style: {
                            width: '300px', height: '20px',
                            background: '#e4f3f7',
                            border: '2px outset lightgray'
                        },
                        placeholder: 'Search language'
                    }}
                />
            </div>
        </div>
    );
}
 
export default App;


Explanation: 

  • 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:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Autocomplete on select language

Reference: https://www.npmjs.com/package/react-autocomplete

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments