Issue with Material UI Select Box Displaying Selected Option

I'm currently working with the following code snippets:

--- before rendering ---

const fontArray = [
  ["Standard", "Standard"], ["Abril FatFace", "'Abril Fatface', cursive"], 
  ["Alfa Slab One", "'Alfa Slab One', cursive"], 
  ["Chonburi", "'Chonburi', cursive"], ["Comfortaa", "'Comfortaa', cursive"], 
  ["Lobster", "'Lobster', cursive"],   ["Pacfico", "'Pacifico', cursive"]
]

--- during render ---

<FormControl style={{margin: '10px'}}>
  <InputLabel htmlFor="select-font">Font</InputLabel>
  <Select
    value={this.state.font[0]}
    onChange={(evt)=>this.handleFontChange(evt)}
    inputProps={{
      name: 'font',
      id: 'select-font',
    }}
  >
    {fontArray.map((font, index)=>{
      return(
        <MenuItem key={font} value={font}>
          <div style={{fontFamily: `${font[1]}`}}>
            {font[0]}
          </div>
        </MenuItem>
      )
    })}
  </Select>
</FormControl>

In this setup, the current font is stored in the state.

--- How I handle a change in selection ---

  handleFontChange = (event) => {
    this.setState({ font: event.target.value })
  };

Although it seems to be almost functional, clicking on the select box shows an empty dropdown despite having valid data in the state:

https://i.sstatic.net/VBNVn.png

What could potentially be causing this issue? Could it be related to how material-ui processes styled text inputs?

Solution Update:

The solution by replacing

<MenuItem key={font} value={font}>

with

<MenuItem key={font} value={font[0]}>

seems to resolve the display issue but causes confusion with state handling. Attempting to address this through the handle function:

handleFontChange = (event, fontArray, stateData) => {
    let newFont = fontArray.filter(i=>{
      if(i[0]==event.target.value){
        return i
      }
    })
    this.setState({ font: newFont })
  };

However, this adjustment still doesn't fully resolve the select box issue. Further refinement may be required for a complete resolution.

Further modifications provided by another solution:

renderValue = (value) => {
    return(
      <div style={{fontFamily: `${value[1]}`}}>
        {value[0]}
      </div>
    )
  }

and

<...>
<Select
value={this.state.font}
renderValue={() => this.renderValue(this.state.font)}
<...>

result in...

https://i.sstatic.net/MBb6t.png

Answer №1

If you are looking for a solution, consider using renderValue.

renderValue = (value) => {
    return value && value[0];
}

within the render method

    <FormControl style={{margin: 10}}>
       <InputLabel htmlFor="select-font">Font</InputLabel>
       <Select
         value={this.state.font}
          renderValue={() => this.renderValue(this.state.font)}
          onChange={evt => this.handleFontChange(evt)}
          inputProps={{
            name: "font",
            id: "select-font"
          }}
        >
        {fontArray.map((font, index) => {
        return (
         <MenuItem key={index} value={font}>
          <div style={{fontFamily: `${font[1]}`}}>
            {font[0]}
          </div>
         </MenuItem>
         );
        })}
      </Select>
    </FormControl>

Answer №2

<...>
<Select
value={this.state.font?this.state.font :defaultvlue}
renderValue={() => this.renderValue(this.state.font)}
<...>

Utilize the ternary operator to display either the data or a default value if no data is present.

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

Height of the div dynamically increases upwards

Just a quick question - is there a way to make position: fixed divs at the bottom of an element (such as the body) grow upwards as content is dynamically added? Maybe something like anchor: bottom or increase: up? I'm thinking that using JavaScript m ...

Is it possible for GraphQL to communicate with an external API?

I am a beginner in the world of GraphQL and have been wondering if I can utilize it to fetch data from an external, third-party API. Currently, I have an express backend and a react frontend set up and I am making a GET request to a third party API to retr ...

The website image does not display at its full size when viewed on a phone

I'm new to working with html and css, and I've encountered an issue with my website regarding image display on both phones and PCs. When viewing the site on a phone, I notice that the full size of the picture is not visible, most likely due to th ...

What is the best way to completely eliminate a div from a webpage

I've created a new div element using jQuery: $(document.body).append('<div id="test"></div>'); Then, I display a success message and remove the div after 10 seconds: $('test').html('SUCCESS!'); setT ...

The export module in a React application is reporting a "Module not found" error when trying to load the

When using mui with named exports, I encountered the error of a module not found issue. I followed this Mui blog post and tried the babel-plugin approach, but the error persisted. package.json "dependencies": { // List of dependencies here ...

Mastering card sliding and spacing in React NativeLearn how to effortlessly slide cards horizontally in your React

My aim with the following code snippet is to achieve two objectives: Apply a margin of 20 units to each card Display all four cards in a single row, allowing users to swipe horizontally Unfortunately, I have not been successful in achieving either of th ...

Using React Typescript to create a button component with an attached image

I am currently utilizing React with Typescript. How can I incorporate an image into my button? I've attempted to do so without any errors, but the button appears blank. What's the best way to style my button element using Emotion CSS in this ...

Cannot utilize Map within each loop

Below is the less code snippet: @threshold:{ a:50; b:200; }; @themes:{ a:red; b:blue; }; .mymixin(@name,@color,@thrshld){ //do-something } each(@themes,{ .mymixin(@key,@value,@threshold[@key]); }); Upon executing the code, an error message ...

React Modal consistently selects the identical record from a row

I am having an issue with my table that displays multiple jobs from an API call. Each row has a button that should open a modal showing more information about the specific job, but it always opens the modal for the row with the lowest id. Can anyone help m ...

Changing text color dynamically when hovered over by referencing retrieved data

Hello, I'm having trouble with applying a className based on database values and using it in CSS for custom hover color. Can anyone assist me? ...

The design of Next.js takes the spotlight away from the actual content on the

Recently, I've been working on implementing the Bottom Navigation feature from material-ui into my Next.js application. Unfortunately, I encountered an issue where the navigation bar was overshadowing the content at the bottom of the page. Despite my ...

Show the exact file name for the CSS file being generated by grunt-contrib-compass

I need help specifying the output name of the CSS file in my grunt-contrib-compass task. Currently, it outputs as index.css. Current Output <%= yeoman.app %>/specialdir/themes/index.css Desired Output <%= yeoman.app %>/specialdir/themes/my-th ...

Scroll to make the div slide in from the bottom

I'm trying to achieve a similar effect like the one shown in this website (you need to scroll down a bit to see the divs sliding in). Although I'm not very proficient in JS, I was able to create a code that makes the divs fade in from 0 opacity ...

Image in an Outlook email surrounded by padding and enclosed in a paragraph

I am facing an issue with my email signature setup in Outlook Live where there is a white space below the image. After trying to add vertical-align:bottom to the CSS, it seems that Outlook Live does not accept it. The code for my HTML in Outlook 20xx is a ...

dispatch a WebSocket message within a route using Express.js

The Objective: Imagine a bustling marketplace with multiple shops. I'm working on a dedicated page localhost:3000/livePurchases/:storeId for shop owners to receive real-time notifications whenever they make a new sale. https://i.stack.imgur.com/VdNz ...

Creating a system of multiple higher-order components in React without relying on Redux

Understanding the purpose of the function name, it is meant to simply add global components. export default withLoading(withSnackbar(GlobalDropZone)); I had a similar question as seen in this React Multiple Higher-Order Components thread but couldn't ...

Change the width of a div element without causing text to wrap when resizing the browser window

Looking to create a layout with three div elements, each containing an h1 element. The goal is to have the first div on the left side, the second div in the center, and the third div on the right side, all in a single row. When the window is resized for re ...

Steps to adjust the visibility of an element by modifying its classname

I have this specific class called: .mapboxgl-ctrl-geocoder { font-size: 18px; line-height: 24px; font-family: "Open Sans", "Helvetica Neue", Arial, Helvetica, sans-serif; position: relative; background-color: #fff; width: 100%; min-width: 240 ...

How to accurately determine the width of an element using JavaScript

Consider this scenario where I have created a custom dropdown list using HTML within a generic div: $(document).ready(function() { $("#selectbox-body").css("width", $("#selectbox").width()); }); <script src="https://ajax.googleapis.com/ajax/libs/ ...

Issues with registering double brackets in Angular.js HTML are causing some problems

After delving into angular.js recently (and I use the term "delve" loosely), I have been working on creating a basic website and hit a roadblock with form validation. It seems that the double bracket notation I picked up from "Shaping up with angular.js" i ...