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

Two components, one scroll bar, both moving within the same plane

For those interested, here is the JSFiddle link for further exploration: https://jsfiddle.net/q6q499ew/ Currently, there is a basic functionality in place where when you scroll past a certain point, an element becomes stuck until you start scrolling back ...

Is there a way to make changes to a pre-uploaded PDF document?

I'm looking to include a footer in a PDF file that is currently stored on the server. For instance, I have uploaded a file to uploads/aaa.pdf and now I need to insert a footer into the same file located at uploads/aaa.pdf Does anyone know how I can ...

Even though I am attempting to submit a form without refreshing the page using Ajax, it is still causing

I've searched high and low, read through numerous examples on various forums, and attempted to find the solution to my query but unfortunately, it still eludes me. Here's the particular scenario I'm facing: Main.php The main.php page featu ...

How to Implement Transition Effect for Height Changes on v-if in Vuejs

I have a code snippet that effectively animates a v-if element by reducing its height to 0px. The animation is working well, but the issue arises when I need to specify the initial height of the element in CSS. While this is fine for a single element, I ...

JavaScript Promise Fundamentals

While I am quite familiar with coding in JavaScript, the benefits of promises in the JS world still seem somewhat unclear to me. Below is an example of asynchronous calls using callbacks nested within each other. (function doWorkOldSchool() { setTime ...

Dealing with a jQuery/Javascript/AJAX response: sending a string instead of an integer as a parameter to a

Trying to figure out how to handle passing integers as strings in JavaScript within an AJAX response. Here is the code snippet: message+="<td class='yellow' onclick='open_flag("+i+j+")'>"; The message variable is eventually inse ...

Align a button to the left or right based on its position within the layout

On the left side, there is dynamic text and on the right side, a button is displayed as shown below: <div class="dynamic-text"> {{ dynamicText }} </div> <div class="some-button"> < ...

Modify the background color of a specific bar across multiple charts when hovering or clicking - utilizing chart.js

I have multiple chart.js canvas elements on a webpage. The goal is to be able to quickly identify and highlight the same bar value across all the charts. For example, when I hover over a bar called "Thu" on the first chart, I want to automatically search f ...

State loss occurs when moving to a different page using next/link

Currently, I am working on a library application with Next.js. Within this project, there are two main pages: BooksPage, which displays a list of all books, and BookPage, where detailed information about a specific book is shown. The components involved in ...

Combining multiple conditions with Sequelize in a JOIN statement

Currently, I am attempting to execute a query using Sequelize ORM with a custom join condition. For example: User.findAll({include: [{model: Post, where: {active: true}}] Here is the result of the join condition: INNER JOIN `posts` AS `post` ON `users`.` ...

Is it possible to dynamically change HTML content by utilizing a JSON file?

Looking to implement a JavaScript loop (using jQuery) that can dynamically populate the HTML file with content from a JSON file based on matching <div> ids to the JSON "id" values. The solution should be scalable and able to handle any number of < ...

Leverage the power of jQuery to fetch data from a PHP script connected to a MySQL database

It might be a bit confusing, so let me clarify. I'm working on a form where users input a ticket and it gets assigned to a technician based on the service they offer. I have 3 text fields: username, email, and description of the problem. The next fie ...

Looking to incorporate Functional Components in React using the package "@types/react" version "^18.0.17"? Learn how here!

With the removal of the children prop from React.FC type, what is the new approach for typing components? ...

Validating American phone numbers using regular expressions

I came across a Javascript regex that is used to validate the different formats in which US phone numbers can be written. However, there seems to be an issue with it: it fails to match the second rule within this specific group: The first group of three ...

What is the method for displaying the delete icon, a child component located within the Menu Item, upon hovering over it using Material UI CSS syntax?

My goal is to display the delete icon when hovering over a specific menu item that is being mapped using the map function. The desired functionality is for the delete icon to appear on the corresponding menu item when it is hovered over. I attempted to i ...

Generating separators in every third row using an array of card elements

https://i.stack.imgur.com/PIMR2.png Hey everyone, I'm working on creating a Divider for every row of 3 items. Currently, my setup only handles two sets of rows, but there could be an unlimited amount of rows that need this divider. I am using slice t ...

Real estate listing featuring unique symbols

How do I include the ' character in properties when writing my object, like this: const championsList = { Kha'Zi: '...', }; Any suggestions on how to achieve this? ...

Challenges with Knockout.js Virtual Elements in Different Environments

I am facing a peculiar issue where a virtual knockout template fails to bind correctly when accessed remotely, yet functions perfectly when viewed locally. You can find the problematic page here: Here is the template I am using: <ul> <!-- k ...

The art of applying styles through styled components

I am attempting to customize the styling of my component with the following code: export const StyledCascader = styled(Cascader)` background-color: gray; ul.ant-cascader-menu { background: red !important; } `; Despite using styled components ...

What issue is present with this AJAX query?

Can you help me figure out where I went wrong with this AJAX code example that I'm trying to learn from? function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new ...