Changing font color of a selected item in Material-UI's textview

I have a select textview in my react app and I am wondering how to change the font color after selecting an item from this textview.

<div>
        <TextField
          id="standard-select-currency"
          select
          fullWidth
          label="Filter By"
          InputLabelProps={{
            shrink: true,
            style: { color: "#fff" }
          }}
          margin="normal"
          value={this.state.filter}
          onChange={this.handleChange("filter")}
        >
          {currencies.map(option => (
            <MenuItem
              key={option.value}
              value={option.value}
              selected
              classes={{ selected: classes.selected }}
            >
              {<div style={divStyle}>{option.label}</div>}
            </MenuItem>
          ))}
        </TextField>
      </div>

For example purposes, here is a demonstration that I have created.

import React from "react";
import Button from "@material-ui/core/Button";
import Menu from "@material-ui/core/Menu";
import MenuItem from "@material-ui/core/MenuItem";
import { withStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";

const homePageStyle = theme => ({
  root: {
    width: "300px"
  },
  selected: {
    backgroundColor: "turquoise !important",
    color: "white",
    fontWeight: 600
  }
});

const divStyle = {
    color: "red"
};

const listStyle = {
  color: "black"
};

const currencies = [
  {
    value: "USD value",
    label: "usd label"
  },
  {
    value: "EUR value",
    label: "eur label"
  },
  {
    value: "BTC value",
    label: "btc label"
  },
  {
    value: "JPY value",
    label: "jpy label"
  }
];

class SimpleMenu extends React.Component {
  state = {
    anchorEl: null,
    filter: ""
  };

  handleClick = event => {
    this.setState({ anchorEl: event.currentTarget });
  };

  handleClose = () => {
    this.setState({ anchorEl: null });
  };

  handleChange = name => event => {
    this.setState({ [name]: event.target.value });
    console.log(name + "   " + event.target.value);
  };

  render() {
    const { anchorEl } = this.state;
    const { classes } = this.props;

    return (
      <div>
        <TextField
          id="standard-select-currency"
          select
          fullWidth
          label="Filter By"
          InputLabelProps={{
            shrink: true,
            style: { color: "#fff" }
          }}
          margin="normal"
          value={this.state.filter}
          onChange={this.handleChange("filter")}
        >
          {currencies.map(option => (
            <MenuItem
              key={option.value}
              value={option.value}
              selected
              classes={{ selected: classes.selected }}
            >
              {<div style={divStyle}>{option.label}</div>}
            </MenuItem>
          ))}
        </TextField>
      </div>
    );
  }
}

export default withStyles(homePageStyle)(SimpleMenu);

In this specific scenario, initially the font color appears as red when opening the dropdown list. However, upon selection of an item, the main label displays the selected item with a red font color which you want to appear as blue instead. How can this customization be achieved?

Answer №1

I'm not well-versed in React, but how about experimenting with some CSS like this?

<select>
    <option>Choose</option>
    <option selected>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
</select>

And here is the corresponding CSS:

select { 
    color: black;
    background: red; 
   }
option:not(:checked) { 
      background: green;
 }

Feel free to check out this JSFiddle for a live demo!

Answer №2

I have discovered the solution. Just include

InputProps={{
            classes: {
                input: classes.input
            }
        }}

within your TextField and specify the desired color in classes.input. This will result in the TextField appearing like this:

<TextField
          id="standard-select-currency"
          select
          fullWidth
          label="Filter By"
          InputLabelProps={{
            shrink: true,
            style: { color: "#fff" }
          }}
          InputProps={{
            classes: {
                input: classes.input
            }
        }}
          margin="normal"
          value={this.state.filter}
          onChange={this.handleChange("filter")}
        >

and the homePageStyle will be defined as follows:

const homePageStyle = theme => ({
  root: {
    width: "300px"
  },
  selected: {
    backgroundColor: "turquoise !important",
    color: "white",
    fontWeight: 600
  },
  input:{
    color: "blue",
  }
});

Finally, make sure to remove style={divStyle} Otherwise, only that style will be displayed.

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 is the best method to generate polar charts using highcharts-react-official?

I'm having trouble creating a polar chart using the HighchartsReact wrapper in my project. Instead of getting the desired result, I either end up with a regular line chart or run into errors. Can anyone help me understand how to utilize the highcharts ...

Transferring data from SocketIO to Vue.js

Is there a way to effectively transfer data results received from socketIO to the Vue instance? Below is my current code implementation: let socket = io(); let users; socket.on('user-connected', (data) => { users = data.count; }); socket ...

Guide on merging all Vue js functions into a single js file?

As a newcomer to vue.js, I am in the process of consolidating several functions into one js file. Here is an example: example.js: function containObject(obj, list) { for (let i = 0; i < list.length; i += 1) { if (list[i] === obj) { return ...

Save the ID of the list item by wrapping it and storing it in a table cell

I need help with a situation where I have a list of items stored in table cells, and each cell contains a list item. My goal is to save the id of each list item into the cell that contains it. For example: <td><li id='itemID'>content ...

Style sheets for two dynamically-sized boxes side by side

There are two boxes or columns positioned on the same line. Both have varying widths that need to remain on the same row. To clarify: .----------container 570px-----------. |[box1] [box2]| Ideal scenario | ...

Transferring temporary information from server to controller using angular-file-upload

Currently, I am utilizing the angular-file-upload library which can be found at this link: https://github.com/danialfarid/angular-file-upload. In the example provided on that page, data from a file is sent to the backend from a controller using the availab ...

Display the user IDs associated with each historical route

Utilizing the react-ga npm module, I successfully integrated Google Analytics into my React website. Through this implementation, I have been able to produce user reports as well as page view analytics. https://i.stack.imgur.com/CWwQE.png I specifically ...

Dynamically add index to attribute as it updates

Having an issue with my dynamic button element: <button v-on:click="changeRecord(element)" v-b-modal.modal-5>Aendern</button> This button is generated dynamically within a v-for loop. Instead of manually including the attribute name like v-b- ...

Command for controlling volume in DiscordJS

Despite my efforts, I am struggling to write a command that successfully changes the volume of the music being played. Every time the player and resource variables in the volume() function are empty while the bot is playing the song. What can I do to resol ...

Reactjs - Enhance user experience with seamless master-detail navigation: Ensuring that the master component remains in the same

On my Master Page, I have a list that displays 100 items initially. The user can click on a load more button to append another 100 items to the list. However, as the list grows longer, scrolling through all the items can become tedious. While scrolling th ...

Different custom background images for every individual page in Nuxt

Looking for a unique background-image for each page in my app is proving to be challenging. Currently, I have defined the background-image in style/app.scss. @import 'variables'; @import 'page_transition'; @import url('https://f ...

Enforcing object keys in Typescript based on object values

I'm looking to design a structure where the keys of an object are based on values from other parts of the object. For example: type AreaChartData = { xAxis: string; yAxis: string; data: { [Key in AreaChartData['xAxis'] | AreaChart ...

Generate a CSV file using Javascript

I am working with an HTML table (table id='testTable') and a button in the HTML code: <button id="btnExport" onclick="javascript:xport.toCSV('testTable');">CSV</button> There is also JavaScript code involved: toCSV: func ...

In order to locate a matching element within an array in a JSON file and update it, you can use Node

Good day, I have a script that updates the value in a JSON file const fsp = require('fs').promises; async function modifyNumberInFile() { try { let data = await fsp.readFile('example.json'); let obj = JSON.parse(dat ...

The functionality of php.js is compromised

I've been attempting to integrate php.js into my scripts, but have encountered a problem. I debugged a function and loaded it onto a single page containing only jQuery and php.js, yet it is still not functioning properly. <script src="http://code. ...

I would like to check if a given username and password exist in my JSON data

Trying different methods but not achieving the desired outcome. I have limited knowledge about JSON, gathered some information from online sources. var loginDataList = [{ "username": "abc", "password": "abc123" }, { "username": "richa", "p ...

Prioritize Correcting Input Errors During Form Submission

Is there a way to automatically focus on the first field with an error when a form submission fails validation? I currently have shouldFocusError: true in my useForm configuration, but the input does not get focused when I click submit after validation tr ...

Fetching Data Using Cross-Domain Ajax Request

Seeking assistance with a cross-domain Get request via Ajax. The code for my ajax request is as follows: var currency_path = "http://forex.cbm.gov.mm/api/latest"; $.ajax({ url: currency_path, crossDomain:true, type:"GET", dataTyp ...

To modify the color of the breadcrumb navigation bar from purple to #d6df23 using PHP

Can someone help me figure out how to change the color of the bar displayed in this link: I need assistance with modifying the breadcrumb navbar. Is there a way to change the color to yellow? I attempted editing the header file, but it didn't produ ...

What are the advantages of using interfaces in React?

Exploring Typescript's interface and its application in React has been an interesting journey for me. It seems that interfaces are used to define specific props that can be passed, acting as a form of protection against passing irrelevant props. My qu ...