Mendes
Mendes

Reputation: 18561

ReactJS change color of the selected option in a select option control

I´m trying to style the text and background color of a control using ReactJS. Here is my ReactJs code:

   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>

          );
      }
    }

And my CSS:

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

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

I can´t style the row that is selected ('3' in the example), no matter what I try. It remains gray and I expect it to has red background with white chars.

How can I style the selected row ?

Upvotes: 1

Views: 6999

Answers (1)

Alesia
Alesia

Reputation: 21

JSX:

class Test extends React.Component {
  state = {
    option: "3"
  }

  handleOptionsChange = (event) => {
    this.setState({
      option: event.target.value
    });
  }

  render () {
    return (  
        <select size={5} value={this.state.option} onChange={this.handleOptionsChange}>
          <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>
     );
  }

And this is the CSS:

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

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

Here is a working demo: https://jsfiddle.net/69z2wepo/96971/

Upvotes: 2

Related Questions