"Concealing specific choices in Autocomplete with reactjs: A step-by-step guide

I am looking for a way to hide the selected option in a Dropdown menu so that it does not appear in the next dropdown. For example, if "Hockey" is selected in the first dropdown, it should not be displayed in the second dropdown; only "Baseball and badminton" should be visible.

This is how my JSON data will look:

"details": [
      { "id": "12wer1", "name": "ABC", "age": 15, "game": "badminton" },
      { "id": "78hbg5", "name": "FRE", "age": 21, "game": "Hockey" }
    ]

Below is a sample code snippet:

let games = [{ game: "Baseball"}, { game: "Hockey"}, { game: "badminton" }];

class Field extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      details: [{id: '', name: '', age: '', game: ''}]
    }
  }
  
  render() {
    return (
      ...
      {this.state.details.map((y) => (
        <Autocomplete
          style={{ width: 200 }}
          options={games}
          getOptionLabel={(option) => option.game}
          onChange={(value) => this.onGameChange(value, y.id)}
          value={games.filter(i => i.game === y.game)}
          renderInput={(params) =>
            <TextField {...params} label="Games" margin="normal" />
          } 
         />
       ))}
     )

   onGameChange = (e, id) => {
     let games = this.state.details;
     let data = games.find(i => i.id === id);
     if (data) {
       data.game = value.game;
     }
     this.setState({ details: games });
   }

   

I am unsure about how to proceed with hiding the selected option. Can someone assist me with this issue? Thank you in advance.

Answer №1

To address this issue, one approach could be:

  • Start by creating an array to store the selected values when the user chooses autocomplete.

  • When passing options, filter out any values that have already been passed to other autocompletes.

     const selectedValues = [111,222,333];
    
     let objects = [{id: 111},{id: 222}];
    
     const index = 1; // representing the current loop index
     const newSelectedValues = selectedValues.slice()
     newSelectedValues.splice(index,1);
     console.log(objects.filter((obj) => !selectedValues.includes(obj.name))); // Use this filtered list for our autocomplete options
    

Answer №2

It's simple to hide this using CSS alone, no ReactJS required

The autocomplete is rendered as an unordered list, so you can achieve the desired effect with the following code:

.panel > ul > li:first-child {
 display:none;
}

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

Upon initiating a React Native project, five critical vulnerabilities become apparent

Upon starting my React Native project, I encountered 5 high severity vulnerabilities. Despite attempting to fix them with the command "npm audit fix --force", the issue persisted. I even went as far as reinstalling node.js and React Native, but the vulne ...

How does the size of a font affect the amount of screen space a character occupies in pixels?

I am currently working on a custom user interface that requires precise measurement of how many pixels are taken up by a specific string of text. My attempts to control the character size using the font-size property have been met with unexpected results. ...

Guide on triggering CSS @keyframes animations upon element visibility while scrolling

I'm struggling with controlling CSS animations that I want to start only when the element becomes visible on the screen. The issue arises because I have a website with a total height of around 8000px and the element with the animation is located far d ...

Adjust the background color in HTML emails for dark mode on mobile devices

How can I ensure that the HTML email maintains a normal white background even when mobile dark mode is turned on? I have included the following meta tag and media queries in my code: <meta name="color-scheme" content="light dark"> <meta name="supp ...

As each new line is added, the span text starts from the bottom and moves up by one line

I am facing an issue where I want a span to start from the top and expand as the text length increases, but it is currently starting from the bottom and moving upwards. See the image below for reference: View Image <div style="width:70%;margin-left: ...

Adjust the transparency of CSS elements using a jQuery selector

I am developing a grid of brand thumbnails with interactive icons. When one of the icons is hovered, I want all the icons to change opacity and become visible. Here is the current HTML structure: <div id="brands-wrapper"> <img class="brands" ...

What steps should I follow to update my NextJS version from v11 to v13?

I am currently working on upgrading the dependencies of my NextJS project to address security vulnerabilities using npm v9.5.1. The reason behind this task is the detection of a security issue by npm audit in my project: node-fetch <2.6.7 Severity: hi ...

Link the user interface to the server logic in a MERN stack web platform

Check out the Github repository for this simple stock management system built on the MERN stack by visiting this link. Within the repo, you'll find two folders - one for the frontend and one for the backend. While it functions smoothly on localhost, t ...

Unable to provide a local storage value within a React component

I am currently creating an email form where, upon submission, I aim to save a Boolean value to local storage to prevent visitors from sending multiple times. However, instead of achieving this, I encountered a blank page and an "undefined" value. Here is ...

The construction of the Gatsby site encountered a major obstacle

I've been facing challenges while trying to build my Gatsby site. Whenever I run 'gatsby develop' in the console, my app starts without any issues. However, when I attempt to build it, I encounter errors like the ones shown below. Does anyon ...

Troubles arise with npm start and Installing Packages: Alert regarding babel-preset-react-app Dependency and Stuck Audit Fix in VSCode

Every time I execute npm start, I encounter the following message: When running npm start, I receive a warning about one of the dependencies, babel-preset-react-app, importing the "@babel/plugin-proposal-private-property-in-object" package withou ...

Tomcat hosting a dynamic duo: Spring Boot and React!

Exploring the world of Spring Boot application development with a React client using Gradle is an exciting journey for me as I navigate through these new technologies. My current progress includes successfully creating a WAR file that encompasses several i ...

Modify the size of the text in an <iframe> using inline css

After attempting the command below, I noticed that the text size within the iframe remained unchanged. Is there a different method to adjust it? <iframe id="myiframe" src="**" height="230px" scrolling="no" style ...

Steps to eliminate pre-chosen alternatives upon loading select control?

When using react-select with pre-selected options and multiple select enabled, the issue arises where clicking on the Select box still displays the already pre-selected options. How can I remove these duplicate options from the list? Below is a snippet of ...

Simulating dynamic route parameters in the Next 13 application directory

I am currently working with Jest and testing library to conduct unit tests on my NextJS application. I am facing difficulties in rendering a page on a dynamic path. Here is the code for my page/component: export default async function MyPage({ params }: { ...

Tips for creating the appearance of a resizable element

My goal was to replicate the resizing and moving functionality of elements in Adobe Illustrator using CSS alone. Unfortunately, I couldn't find any useful resources on how to achieve this. ...

Guidelines for retrieving a class name using jQuery when hovering over a div

I need assistance in fetching the class name by hovering over a div. Both divs have the same id but slightly different class names. Here is an example: <div id="1-someid" class="1-example-class border cz"> ...more elements go here.... </div> ...

What is the best way to insert an image in front of text within a table cell that can be identified by its class name?

JavaScript Question: function addFlags(){ while(i < $('.tabledata').length){ var current_val = $('.tabledata').eq(i).text(); arr.push(current_val); $('.tabledata').eq(i).html("<img s ...

The flex-wrap property with a value of "nowrap" does not seem to

I am struggling with making the page responsive. The flex-wrap: nowrap property seems to be causing issues. Can someone please assist me in identifying the root of the problem? .logo { text-decoration: none; color: white; } .header { width: ...

What is the reason behind changing the line-height for one inline-block sibling div affecting both divs?

Here's my setup: <div> <div style="display:inline-block; ">div_1</div> <div style="display:inline-block; line-height:20px;">div_2</div> </div> Why does setting the line-height property f ...