Is there a way to retrieve the total count of the selected options using Autocomplete in material-ui?

Is there a way to show the total count of chosen options using the Autocomplete feature from material-ui?

If so, how can I achieve this?

Simply follow these steps: click on Open menu dropdown, open the Autocomplete, select your desired options, and you will see the total number next to Selected:X.

The value of X will be the actual count.

For a working example, check out this demo

export default function ClickAway() {
  // Functionality code, react components...
}

const top100Films = [
  { title: "Select All", value: false },
  // List of movie titles and years...
];

Answer №1

To implement this functionality, you can utilize the concept of controlled state for the Autocomplete.

  1. Start by creating a state variable. If multiple selections are allowed, the value should be stored in an array.
const [selectedValue, setSelectedValue] = React.useState([]);
  1. Add the value and onChange props to your Autocomplete component:
value={selectedValue}
onChange={(event, newValue) => {
    setSelectedValue(newValue);
}}
  1. Utilize the selectedValue to track the number of items selected:
<span>Selected: {selectedValue.length}</span>

You can view an updated version of your code with this approach here: https://codesandbox.io/s/controlled-autocomplete-nfbyyw?file=/demo.js.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Organize information in a React table following a predetermined sequence, not based on alphabetical order

As a beginner with React, I'm looking to sort my data by the column "Status" in a specific order (B, A, C) and vice versa, not alphabetically. The data structure looks like this: export interface Delivery { id: number; name: string; amount: num ...

What are some possible reasons for an API fetch failing to retrieve data from a URL, and what are potential solutions to address this issue?

Struggling to retrieve data from the server using frontend code. Below is an example of fetching user details, but it's not functioning as expected. const UserDetails = async () => { const apiUrl = process.env.REACT_APP_API_URL; try { cons ...

Create a list using ReactJS

I've been working on rendering a dynamic list in JSX, but I'm facing issues displaying the items. Below is my code snippet where I attempted to use useState const [orderList, setOrderList] = useState([]) and setOrderList(prev => [...prev, chil ...

Navigating through the React components using react-router and accessing the props can

Is there a way to access this.props from the <Router>'s onUpdate function? I need to know the current route and access this.props.route in order to identify the page (name). Unfortunately, I haven't found any resources on how to achieve thi ...

Enhance MUI Google Maps Autocomplete by incorporating additional parameters

Hello everyone, I'm currently diving into the world of React and have recently embarked on using the Google Maps Autocomplete API by following the MUI example. One thing I can't seem to figure out is how to configure the autocomplete feature to o ...

Incorporating an external SVG link into a React application

While I may not be an SVG expert, I haven't encountered any issues with loading SVGs in my React app so far. I prefer using the svg tag over the image tag because sizing tends to present problems with the latter option when working with external links ...

When I engage with the input field, it ceases to be in focus

Here is the code I've been working on: https://github.com/Michael-Liendo/url-shortener/blob/main/src/pages/index.js If you want to see the issue for yourself, check it out at: ...

What is the best way to utilize the properties obtained from a spread operator?

I am encountering a confusing issue in my code. I am passing an object as a prop and then taking it as a param. Passing props Taking it as a param Console logging the prop Initially, everything works as expected. However, when I use the spread operato ...

The parameter 'prev: todoType[] => todoType[]' cannot be assigned to the type 'todoType[]'.ts(2345)

An issue has arisen with this.props.update as mentioned in the title import { useState } from "react"; import axios from "axios"; import { todoType } from "../../types/todo"; type sendResponse = { task: string; }; type getRe ...

Incorporate a fresh element into an object after its initial creation

Hello, I am looking to create an object in JavaScript that includes an array-object field called "Cities." Within each city entry, there should be information such as the city's name, ID, key, and a District array object containing town data for that ...

Having trouble retrieving a value from a .JSON file (likely related to a path issue)

My React component is connected to an API that returns data: class Item extends Component { constructor(props) { super(props); this.state = { output: {} } } componentDidMount() { fetch('http://localhost:3005/products/157963') ...

Adding property to an object retrieved from an API in a React application can be achieved effortlessly by utilizing the useState

How can I implement a toggle functionality for Bookmarked Meals on my Meal Recipe Website available at ? I am currently using the logic to set data.meals[0].bookmarked to true or false, but I want to use setState instead in order to rerender the page when ...

Can we not customize a nested component using the 'styled()' function in MUI?

Looking at the code snippet below, my attempt to style an MUI Stack component within an MUI Dialog component seems to be falling short. The Stack styles are not being applied as expected: const CustomDialog = styled(Dialog)(({ theme }) => ({ ' ...

Develop a React component library and seamlessly integrate it into a Next.js project

Currently, I am in the process of building a component library using react js, vite tailwindcss, and antd. The components function flawlessly when running the project locally or within Storybook. However, upon importing them into another nextjs application ...

Are you facing difficulties while trying to utilize useContext in your React application?

I have a basic React application where I need to implement useContext. (by the way, I am using Vite + React) Below is the code for my Context.jsx file: import React, {useContext} from 'react'; const emailContext = React.createContext(); expor ...

Customize the antd theme in a create-react-app project without the need to eject webpack

Struggling with customizing antd in my react app. I'm hesitant to mess with the webpack config.js file since I'm not well-versed in webpack. My goal is to avoid having a site that looks like a generic antd clone, but all my attempts at customizat ...

The makeStyles function is unable to interact with dynamic CSS variables

const customStyles = makeStyles({ box: { color: "var(--custom-text) !important", }, }) The CSS variable var(--custom-text) is dynamically changing within the application based on a user toggle. However, the component utilizing this custo ...

The function auth.createUserWithEmailAndPassword is not recognized in the context of React

base.jsx: import { initializeApp } from "firebase/app"; import { getAuth } from "firebase/auth"; const firebaseConfig = { config }; export const app = initializeApp(firebaseConfig); export const auth = getAuth(); Register.jsx ...

show the stored value inside the useRef variable

One of my challenges involves a variable const prediction = useRef<any>(null); A button triggers a function that updates the variable's value: function showResult() { classifier.current.classify(capture, (result) => { ...

When comparing two state arrays in React, it is important to note that they will not be considered equal and return a boolean (True

As I attempt to compare two arrays stored in my state, my goal is to set a boolean variable to "true" if they match. However, my current if statement fails to detect equality between the arrays. I'm performing this comparison within a setInterval() f ...