How to alter the color of the chosen option in a select option control using ReactJS

Struggling to customize the text and background color of a control using ReactJS. Take a look at my code snippet:

   import React, { Component } from "react";

   import "./Test.css";

    class Test extends Component {

      render = () => {

        return (  
            <select size={5} value={'3'}>
              <option className='opt' value='1'>Option 1</option>
              <option className='opt' value='2'>Option 1</option>
              <option className='opt' value='3'>Option 1</option>
              <option className='opt' value='4'>Option 1</option>
              <option className='opt' value='5'>Option 1</option>
            </select>

          );
      }
    }

Here's my CSS styles:

.opt { 
    color: red;
    background-color: white;
}

.opt:checked {
    color: white;
    background-color: red;
}

Despite all efforts, I'm unable to change the style of the selected row ('3' in the example), which remains gray instead of having a red background with white characters. Any suggestions on how to achieve this?

Answer №1

Understanding JSX:

class Form extends React.Component {
  state = {
    chosenOption: "3"
  }

  handleOptionChange = (event) => {
    this.setState({
      chosenOption: event.target.value
    });
  }

  render () {
    return (  
        <select size={5} value={this.state.chosenOption} onChange={this.handleOptionChange}>
          <option className="opt" value='1'>Option 1</option>
          <option className="opt" value='2'>Option 2</option>
          <option className="opt" value='3'>Option 3</option>
          <option className="opt" value='4'>Option 4</option>
          <option className="opt" value='5'>Option 5</option>
        </select>
     );
  }

Here are the corresponding CSS styles:

option {
  background: #ffffff;
  color: #ff0000;
}

select option:checked,
select option:focus {
  background: linear-gradient(#ff0000, #ff0000);
  -webkit-text-fill-color: #ffffff;
  color: #ffffff;
}

Take a look at this live demo to see it in action: https://jsfiddle.net/69z2wepo/96971/

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

If I create an App with Phonegap, HTML5, and Websql, what happens to the app's data when the user restarts their mobile device?

My application utilizes HTML5's WebSQL to store temporary notes and bookmarks, which will later be synchronized with the server. I am curious whether data stored in WebSQL will be lost upon mobile restart or cache clear, similar to how browsers on ph ...

Implement a transition effect for when elements change size using the `.resizable().css` method

I attempted to incorporate a deceleration effect when resizing an element back to its original size using the resizable method. The slowdown effect should only trigger during the click event (when the "Click-me" button is pressed), not while manipulating ...

Combining an Image with a CanvasJS Graph and Generating a Downloadable Image of the Composite

I am attempting to combine an image (a background image for my graph) with my canvasJS chart. Once these elements have been merged on a canvas, I aim to obtain a DataURL of this canvas, enabling me to download an image of it (depicting the graph along wit ...

Is it possible to retrieve event.data beyond the onMsg callback function in JS SSE?

My current project involves using three.js to display accelerometer data in real-time and in 3D on a web browser. To transfer data from the remote server to the client side, I am utilizing server-sent-events (SSE). While I have successfully implemented th ...

Set tab navigation widget with a fixed height

I am struggling with setting a fixed height for my tabs widget so that when I add more content, it will display a scrollbar instead of expanding endlessly. I have checked the CSS and JS files but cannot figure it out. It is important for me to contain this ...

Setting the title of a PDF page from a Symfony Controller

My method in a Controller is shown below: /** * @Route("/bilgi/agr", name="user_agreement") */ public function agr(): Response { $response = new BinaryFileResponse(__DIR__ . '/../../public/docs/User_Agreement.pdf'); ...

The backgroundImage function is having trouble locating the specified URL path

I'm struggling to set a backgroundImage because it's not recognizing the local path URL. Here is my code snippet: import { makeStyles } from '@material-ui/core/styles'; const loginWrapperStyles = makeStyles(theme => ({ image: { ...

Stop MUI Autocomplete onChange if the reason is "create-option"

Is there a way to prevent a user from adding an input value to Autocomplete's values array if there is an error with that value, while still maintaining the current input value being typed? I am looking for a solution to cancel the event in such cases ...

Responsive Tabs with Material-UI

Can MUI's Tabs be made responsive? This is what I currently have: https://i.stack.imgur.com/KF8eO.png And this is what I aim to accomplish: https://i.stack.imgur.com/b3QLc.png ...

Handling versioning when a property is deprecated in semver

We've implemented semver for maintaining our CSS libraries, ensuring we adhere to the official guidelines for versioning. However, when we render a class obsolete (or for JavaScript - a property or argument), what is the recommended action? The clien ...

Steps for inserting a button within a table

Currently, I have implemented a function that dynamically adds the appropriate number of cells to the bottom of my table when a button is clicked. This is the JavaScript code for adding a row: <a href="javascript:myFunction();" title="addRow" class= ...

forming a boundary that stands alone, unattached to any other boundaries

I am trying to design a navigation bar that resembles the one depicted in the image provided. The concept involves creating a navigation bar where each border is separated from the others, potentially achieved using hr tags. However, I am struggling to fi ...

How can I modify the preset website design in React.js (vite)?

Whenever I start a new react js project, I am always met with the default template that includes unnecessary code. I find myself spending time navigating through different files to clean it up before I can start building. I've been searching for a bla ...

Join the AWS Chime meeting that has been initiated - learn how to connect now!

I have successfully utilized the Amazon Chime SDK within my React JS application to create meetings and initiate them. Now, I am wondering how others can join these meetings or how additional attendees can be added. ...

Encountered an error: Invalid usage of hooks. Hooks are intended to be called only within the body of a functional component. - issue with useEffect() function

Encountering an error while attempting to call a function imported within the useEffect() hook in Dashboard.jsx. The goal is to fetch data from the database upon page load, ensuring that users can send the correct credentials to the API with a button click ...

CSS and jQuery UI URLs are not resolving properly in MVC framework after deployment

Basically, the issue is that the url for an image in jquery-ui.css file does not resolve once the site is deployed. The website is deployed under the default web site in IIS7, causing the browser console to look for the image in a different location than e ...

Steps for Displaying Error Message when Search Result is Not Found in a JavaScript Table

After creating a table using HTML to display student data like name, degree, and profession, I added a search bar for users to find information on a specific student by typing the student's name. If the student is not in the table, a message "Result n ...

Guide on creating a function in PHP that takes a string input and outputs it in JSON format

Here is an illustration of a data structure that specifies the color of different fruits: array( "red" => array("apple, strawberry"), "yellow" => array("lemon", "ripe mango") ) Create a function called getFruits, which takes a color as input ...

How about utilizing a map with arrays for this object?

Currently, I am delving into the realms of JS and TypeScript with a focus on generating separate React components for specific items. Allow me to introduce you to an example object: var regions = { NA: ["US", "ABC1"], EU: ["GB", "LX", "IT"], F ...