Adding a placeholder to a MUI Select component with different value prop and MenuItem options: a step-by-step guide

Is there a way to include a placeholder (-- Select --) in the MUI Select component below?

const [country, setCountry] = useState("")

<FormControl fullWidth error={!country}>
    <Select
        displayEmpty
        renderValue={selected => selected.length === 0 ? '-- Select --' : selected}
        value={country}
        onChange={e => setCountry(e.target.value)}
    >
        <MenuItem value='US'>America</MenuItem>
        <MenuItem value='CA'>Canada</MenuItem>
        <MenuItem value='UK'>England</MenuItem>
    </Select>
    {!country && <FormHelperText>This field is required.</FormHelperText>}
</FormControl>

After adding the displayEmpty and renderValue props to the Select component, there was an issue where selecting 'America' displayed 'US' instead of 'America'.

renderValue={selected => selected.length === 0 ? '-- Select --' : selected}

The problem was resolved by adjusting the value props as shown below.

<MenuItem value='America'>America</MenuItem>
<MenuItem value='Canada'>Canada</MenuItem>
<MenuItem value='England'>England</MenuItem>

However, since only country codes will be stored in the database, the values must remain 'US', 'CA', and 'UK'. Does anyone know how to add a placeholder while still displaying the correct option when it's selected?

Answer №1

If you're looking for the best way to achieve this, it is highly recommended to locate the correct label within your object.

Make sure you have an array of countries from which you are obtaining the list. If not already available, please create one.

Each country in the list should have both an `id` and a `label`. When a country is selected (with a selected length greater than 0), search for that country using its `id` in the list and display its corresponding label.

const CountryFormComponent = () => {

...rest of component body

const listOfCountries = [{id : 'US', label: 'America'},
{id : 'CA', label: 'Canada'},
{id : 'UK', label: 'England'},
];

const generateRenderValue = (selected) => {
return (selected.length === 0 ? '-- Select --' : listOfCountries.find((x) => x.id === selected).label);
}

....
//return statement
....
<FormControl fullWidth error={!country}>
    <Select
        displayEmpty
        renderValue={generateRenderValue}
        value={country}
        onChange={e => setCountry(e.target.value)}
    >
        {listOfCountries.map((x) => <MenuItem value={x.id}>{x.label}</MenuItem>}
    </Select>

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

Establishing Node.js environment variables when invoking `npm run` command

package.json { "scripts": { "start": "NODE_ENV=development node ./index.js" } } If we wanted to pass and override NODE_ENV when running npm run start, is it possible? npm run start NODE_ENV=production ...

Ways to add a line break within JavaScript code

I am currently developing a bot for my Discord server and working on logging messages to a text file. All the necessary information about the message is stored in a variable named logger, and I am using Node.js to append my log file. When attempting to ad ...

The makeSVG function from GoJS is failing to generate the correct HTML SVG object

I have been utilizing the Diagram.makeSVG() method to create an SVG from my diagram. Subsequently, I appended the SVG to a new empty tab using this script (diagram represents my Diagram Object): function print() { var newTab = window.open(), svg ...

Script in Javascript halting Internet Explorer's operation

I'm encountering a problem with Internet Explorer freezing due to the following code. This code is part of a project that focuses on handling student grades: var array1 = StudentGradeAreadHugeList(); var nextArrayItem = function() { var grade = ...

When attempting to showcase an MUI icon that was imported, I encounter the following issues: Invalid hook call and the <ForwardRef(SvgIcon)> component

Encountering issues while trying to display an imported MUI icon leads to the following errors: Error: https://i.stack.imgur.com/USdEx.png Sample Code: import React from 'react' import ThreeDRotation from '@mui/icons-material/ThreeDRotati ...

Assistance requested in structuring JSON data

I'm currently working on making my javascript code more dynamic. Here's what I have so far: data.addRows(2); data.setValue(0, 0, 'name goes here'); data.setValue(0, 1, value 1 goes here); data.setValue(0, 2, value 2 goes here); data. ...

The process of masking a video with alpha data from another video on canvas seems to be experiencing a

I have a unique setup on my page where I'm masking one video with another. Essentially, when the Play button is pressed, a second video slowly appears over the looping video in the background. This effect is achieved by using a black/white mask transf ...

Material-UI - JSS style order issue

I am facing an issue where the JSS styles from my MUI component library (Styles A) are taking precedence over the styles provided by a consumer's website (Styles B). The intended behavior is for Styles A to be overwritten by Styles B. Consider this ...

How can jQuery input be incorporated in a form submission?

My current form includes a field for users to input an address. This address is then sent via jQuery.ajax to a remote API for verification and parsing into individual fields within a JSON object. I extract the necessary fields for processing. I aim to sea ...

The validation directive is run on each individual item within the ng-repeat loop

As I develop a single page application utilizing Angular and Breeze, the challenge of managing entities with dynamic validation arises. With a set of entities displayed on the page using data-ng-repeat, I implement in place validation through toggling betw ...

Encountering an issue with the node.js express server when fetching data

I'm running into an issue with the fetch function and node.js. When a button is clicked on my frontend, I want to send a post request to receive an array from my backend as a response. My backend is built using node.js with express, and I'm using ...

Storing various duplicates of items in local storage

Looking for help with storage settings in HTML/JavaScript as I work on a mobile not taking app using Phonegap. My goal is to allow users to input a note name and content, save them into a jquery mobile list, and see them on the home screen. However, I&apos ...

Toggle visibility

Seeking a unique example of a div SHOW / HIDE functionality where multiple divs are populated within the main container. Specifically looking to display new paragraphs or topics of text. I have experience with standard show/hide techniques for collapsing ...

Make sure to include the "active" class in the pager once the slider begins

After coming across this fiddle, I noticed that it closely resembles the task I am working on. However, there is one issue - currently, only the first item has an active class when the slider autostarts. The next or previous items do not receive the acti ...

Save the output of a function in node.js

I have created a function that utilizes the nodejs module recursive-readdir to read all files within a folder recursively. The function is functioning correctly, but I am facing an issue with exporting the 'routes' array using 'module.export ...

Increase the lag time for the execution of the on('data') function in Node.js

In my current function, it searches data from a database and performs an action with it. For the purpose of this demonstration, it simply increments a counter. exports.fullThreads = function(){ return new Promise((resolve, reject) => { MongoClien ...

XPath Selector in Puppeteer version 22.x

Despite poring over the latest Puppeteer v22.x documentation on XPath, I am still struggling to grasp how to effectively utilize XPath in Puppeteer 22.x. My goal is to click on an element that contains the text 'Next'. Here's the HTML snipp ...

One way to add a JSON object to an empty JSON array using Javascript involves pushing

Currently, I am facing an issue with an empty JSON array. shoppingCart: [] In addition to the empty array, I also have a JSON object defined as follows: let product = {"name": "name", "price": "price", "quantity": "quantity", "logoPath": "logoPath"}; M ...

What steps do I need to take to create npm packages specifically for react-native development?

Which programming languages are essential for creating npm packages that work on both android and ios platforms in react-native development? Can you suggest any helpful documentation or blogs for developing npm packages that support ...

Observable<void> fails to trigger the subscriber

I am currently facing a challenge with implementing a unit test for an Observable in order to signal the completion of a process. While there is no asynchronous code in the logout function yet, I plan to include it once the full logic is implemented. The m ...