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

What steps can be taken to resolve the error ERROR TypeError: undefined is not an object when evaluating 'userData.username'?

.I need help fixing this error ERROR TypeError: undefined is not an object (evaluating 'userData.username') Currently, I am working on a small application where users are required to allow permission for their location in order to save their cit ...

Tips for utilizing the 'contains' feature within web elements with Java Selenium WebDriver?

In my current project, I am facing a challenge with two specific elements: one is a string formatted as ABC £12,56 and the other is a box called "Cashbox" that should be 15% of the value of the string. However, when attempting to locate the CSS for both e ...

fresh map from Google: Coordinates LatLng may not be a number, but my hunch tells me it is

Seeking Assistance with this Issue - For example, the initial location data appears as: "Object Lat: -36.768498 Lng: 174.75895" However, an error is indicating that the latitude is not recognized as a number. Rather than making adjustments without clea ...

Having trouble accessing the 'root' property for all components in Material-ui v4

After upgrading from Material-UI v3 to v4, I am encountering an error with every component I import: app.js:3581 Uncaught TypeError: Cannot read property 'root' of undefined at Button (app.js:3581) at renderWithHooks (app.js:126202) ...

Example showcasing the functionality of the react-custom-scrollbars package in a TypeScript React application

In my TypeScript React project, I am struggling to set up the react-custom-scrollbars package successfully. Despite consulting the examples provided in the GitHub repository, I have not been able to get it working. Can someone share a functional example ...

Transform strings in a table into integers within a specified scope

My World.json file is quite large and contains extensive data on countries worldwide. I've been utilizing a list to display this data in a table format, with the intention of sorting all values accordingly. However, I have encountered an issue - all m ...

Exploring the capabilities of data processing in Node.js

I've been attempting to read data from a locally stored JSON file, organize it into individual JS objects, and add them to a queue. However, I'm struggling to find a way to test my parsing function to ensure it's functioning correctly. My cu ...

Create a JavaScript button that redirects to a different page within a React application

I am creating a div element using a for-loop and I want to link each div to the "/campaign" page with its respective id. When a div is clicked, I want it to navigate to the "/campaign/id" page and pass the id to the Campaign component. class Home extends ...

What is the most effective way to inform the user when the nodeJS server can be accessed through socketIO?

I have developed a web app that indicates to the user when the server is online for data submission. Although the current code functions properly for single-user interaction, I am facing an issue where one user's connection or disconnection directly i ...

Error during compilation in npm (symbol '_' is not recognized)

After updating all the dependencies in my JavaScript program without making any changes to my components, I encountered an error when running: npm run build The error specifically mentions a problem with one of my components: Failed to compile. ./src/c ...

What is the best way to deploy Material UI icons on Vercel?

I am currently in the process of deploying my website on Vercel. Everything is functioning properly on my localhost3000, however, when I attempt to deploy it on Vercel, I continuously receive the following error message: "Module not found: Can't resol ...

RxJS Observables trigger the onCompleted function after completing a series of asynchronous actions

I have been attempting to design an observable that generates values from various asynchronous actions, particularly HTTP requests from a Jenkins server, which will notify a subscriber once all the actions are finished. However, it seems like there might b ...

Tips for preventing a table from showing up while scrolling unnecessarily when utilizing a heading with the CSS position property set to 'sticky'

Currently, I am facing an issue with creating a sticky header for my table. The problem arises when the header of the table has rounded edges (top right and top left) along with a box-shadow applied to the entire table. As the user scrolls through the tabl ...

Encountered an error while attempting to load the resource: the server has issued a status of 405 (Not Allowed), seeking assistance with the nginx

I have a fully functional MERN stack app with AXIOS. While the app works perfectly on my localhost, I face issues when deploying it on nginx as all the POST requests are being denied. Despite trying various solutions found online, none seem to be working. ...

execute the NPM script in the current directory

Within my package.json file for a node project, I have the following test script that utilizes the ts-node package: "scripts": { "build": "tsc", "test": "ts-node" } Executing this script from the root ...

Struggling to integrate buttons into an h2 element with the use of createElement() and appendChild() in HTML/CSS/JS

As I work on developing a website, one of the features I've been implementing is the ability for users to add books to a list and then review or delete them. The process was smooth sailing until I reached the point of adding buttons for these actions. ...

Getting row data in datatables after a button click: A step-by-step guide

Could somebody provide assistance with retrieving a single row of data on a click event? This table is dynamically populated after the AJAX call's Success function is executed <div class="table-responsive table-wrap tableFixHead container-flu ...

Customizing Floater Position in React Joyride

How can I modify the floater position for a specific step? I attempted the following code: floaterProps: { styles: { tooltip: { top: -200 }, arrow: { top:-200 } } However, this doesn't seem to be effective! Could you please a ...

Bring google map markers to life with animation

Is there a way to create an animation like the one shown in this example? I'd like for the map to highlight the corresponding place when a user clicks or hovers over a location in the list. How can I make this happen? I've tried searching on Go ...

The interface is incompatible with the constant material ui BoxProps['sx'] type

How can I make the interface work for type const material ui? I tried to register an interface for sx here, but it keeps giving me an error. import { BoxProps } from '@mui/material'; interface CustomProps { sx: BoxProps['sx&apo ...