Auto Suggest: How can I display all the attributes from a JSON object in the options list using material-ui (@mui) and emphasize the corresponding text in the selected option?

Currently, I am facing a requirement where I need to display both the name and email address in the options list. However, at the moment, I am only able to render one parameter. How can I modify my code to render all the options with both name and email?

https://i.stack.imgur.com/Vy4k5.png

This is my current code:

<Autocomplete
    freeSolo
    disabled={false}
    fullWidth={false}
    label={'label'}
    multiple={true}
    componentsProps={{
        paper: {
           sx: {
              border: '1px solid lightgray',
              marginLeft: 10.5,
              width: 484,
           }
        }
    }}
    options={[
      { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="630213130f0623040e020a0f4d000c0e">[email protected]</a>', label: 'apple', value: 'apple' },
      ...
    ]}
    renderOption={React.useCallback((props, option, { inputValue }) => {
      return (
          <Box component='li' {...props}>
              {option.label}
          </Box>
      )
  })}
/>

Answer №1

To customize the highlight option and render email and label, I utilized dangerouslySetInnerHTML. The width was set in the following manner:

<Autocomplete
    options={[
      { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0a1b0b0aca580a7ada1a9aceea3afad">[email protected]</a>', label: 'apple', value: 'apple' },
      { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="adddc8ccdfedcac0ccc4c183cec2c0">[email protected]</a>', label: 'pear', value: 'pear' },
      { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7b8a5b6b9b0b297b0bab6bebbf9b4b8ba">[email protected]</a>', label: 'orange', value: 'orange' },
      { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0c7d2c1d0c5e0c7cdc1c9cc8ec3cfcd">[email protected]</a>', label: 'grape', value: 'grape' },
      { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1775767976797657707a767e7b3974787a">[email protected]</a>', label: 'banana', value: 'banana' }
    ]}
    renderOption={React.useCallback((props, option, { inputValue }) => {
      function boldString(str, substr) {
          const strRegExp = new RegExp(substr, 'g')
          return str.replace(strRegExp, '<b style=color:#1e99fa !important;>' + substr + '</b>')
      }
      return (
          <Box component='li' {...props}>
              <div style={{width: '50%'}} dangerouslySetInnerHTML={{ __html: boldString(option.label, inputValue) }}/>{option.email}
          </Box>
      )
  })}
/>

final result:

https://i.stack.imgur.com/e76rH.png

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

Angular connecting to the count of filtered items

Here's the array I'm working with: [ { type: "hhh", items: [ { "name": "EGFR", "type": "a", "selected": true } ] }, { type: "aaa", items: [ { ...

Error: The term 'RequestCompleted' is not recognized by Microsoft JScript

Does anyone have any suggestions? The error above occurs when this code is executed: Sys.WebForms.PageRequestManager.getInstance().add_endRequest(RequestCompleted); Specifically within this section: <script language="javascript" type="text/javas ...

What are the best practices for managing large amounts of data using jQuery and PHP with AJAX?

When I attempt to pass a large JavaScript array to PHP using the $.ajax method of jQuery, with Content-Type set as JSON and data sent as RAW, I encounter an issue. In PHP, I retrieve the data using file_get_contents('php://input'). Despite every ...

Setting the Content-Type of a JavaScript file within a NodeJS application

I am facing an issue with opening a js-file on my NodeJS server, as it always specifies the .js file with a Content-Type of "text/html." My objective is to send user-input from an html form to a JavaScript file for performing calculations and later genera ...

What is the best way to display the remaining items in an array when a user clicks the next button?

Having a total of 12 cameras, I want to be able to select 4 cameras from a drop-down menu option and have only those 4 cameras displayed. Then, when I click on the next button, I need to show the remaining cameras in the selected layout format. How can thi ...

Guide to setting up eslintrc and integrating React with airbnb and typescript without using the create react app command

My current project does not utilize create-react-app. I am in the process of updating my Eslint configuration. How can I properly add React to the eslintrc.js file? In the extend property, I currently have the following: extends: [ 'airbnb', ...

Trouble with Bootstrap 5 Carousel swipe functionality: Issues arise when inner elements with overflow are involved, causing vertical scrolling to interfere with left to right swipes

I've been scouring the internet for answers to my unique issue with a Bootstrap 5 carousel. My setup is fairly basic, but I've removed the buttons and rely solely on swiping to navigate through the carousel items. When I swipe left to right, eve ...

What is the method for creating a JavaScript array that closely resembles the provided example?

My task is to create an addRows method using specific data structure as shown below. data.addRows([ ['UK', 10700,100], ['USA', -15400,1] ]); However, the data I have available is in a different format. How can I transform ...

How to retrieve the image source from a block using jQuery

Currently, I am working on developing a slider for my webpage using jquery's "Cycle" plugin. However, I have encountered an issue with accessing the image sources used in the slider. To provide more context, here is a snippet of code from the 'he ...

Using NodeJS and EJS to Display MySQL Query Results

I am currently working on a project where I need to display data retrieved from a MySQL query in an HTML table. However, when I attempt to do so, I encounter the following output: [object Object],[object Object],[object Object],[object Object],[object Obj ...

Starting the scroll in React from the bottom

I am currently working on a chat page where incoming messages need to be displayed from the bottom up. I have utilized the useRef hook for scrolling purposes, but I encountered an error in my console stating "TypeError: Cannot read property 'scrollInt ...

How can NodeJS Websocket (ws) facilitate communication between various clients?

In my project, I have a scenario where client1 needs to share information with client2 and the latter should receive an alert upon receiving it. To achieve this, I am utilizing Websocket "ws" with NodeJS. The web page for client1 receives a response via A ...

Switch between Fixed and Relative positions as you scroll

Just a small adjustment is needed to get it working... I need to toggle between fixed and relative positioning. JSFiddle Link $(window).on('scroll', function() { ($(window).scrollTop() > 50) ? ($('.me').addClass('fix ...

Ways to upload an image beyond the Frontend directory

Currently, I have a react project with the following folder structure: - React Project - Frontend - src - public - data - Backend Typically, to load an image, I would place it in the Frontend/public/data folder and reference it in ...

Leveraging various techniques within a single controller in AngularJS

I am seeking assistance and advice on a coding issue I am facing. I am attempting to use two methods in one controller. The first method is to display selected rooms, while the second method is to display selected pax. However, only the first method seems ...

Verify the user's admin role before granting access to a specific page in a web application built with React, Express, NodeJS, and

To ensure that only admin users can access the "Users" page, which displays all registered users on the website, a specific component is needed: <Route path="/users" exact component={Users} /> Although I attempted the following code below, it did n ...

Is it necessary to encode the content before transmitting HTML in JSON from the server to the client?

When it comes to sending HTML content from the server to the client for displaying user comments in a rich JS app that communicates through a JSON API, there are some considerations to keep in mind. One important question is how to handle the content with ...

Looking to streamline a JavaScript function, while also incorporating jQuery techniques

I've got this lengthy function for uploading photos using hidden iFrames, and while it does the job well, it's quite messy. I'm looking to simplify it into a cleaner function with fewer lines of code for easier maintenance. function simplif ...

Designing an architecture for a Java, Android, and database application - what will the final app's appearance be

I am currently working on a website where users need to complete tasks using an Android device: Fill out a simple HTML document. Sign the document on their Android device. Save the data entered into a database on the website. Some key points to consider ...

Tips for saving an image that has been dragged onto the browser locally

I recently started working with Angular and decided to use the angular-file-upload project from GitHub here. I'm currently in the process of setting up the backend for my application, but I'd like to be able to display dropped files locally in th ...