dropdown color in choosen option

2.6k views Asked by At

I am using reactjs. I created dropdown list with style to each value. When I chose option. the color is not appeared in the head of the dropdown. How can I fix this? I know I can add onChange event to the dropdown but I can't figure out what to write in the function.

enter image description here

       render: function(){
       return (
            <div>
               <input ref="textField"></input>
               <select ref="dropDownColor" onChange={this.chageColor}>
                      <option>Color</option>
                      <option value="aqua" style={{color: 'aqua'}}>Blue</option>
                      <option value="red" style={{color: 'red'}}>Red</option>
                      <option value="orange" style={{color: 'orange'}}>Orange</option>
                      <option value="green" style={{color: 'green'}}>Greed</option>
                </select>
                <button onClick={this.addNote}>click</button>
            </div>
       );
   }

Thanks Alon

1

There are 1 answers

0
AudioBubble On BEST ANSWER

First define the state in a constructor like

constructor(props) {
    super(props);
    this.state = {color: 'aqua'};
  }

Then you can define a function that changes the state like this

changeColor(e) {
    this.setState({
        color: e.target.value
    })
}

You can have the select in the render defined like this to call the function and have style equal to the state

<select style={{color: this.state.color}} ref="dropDownColor" onChange={this.changeColor.bind(this)}>

Fiddle showing this here https://jsfiddle.net/ab43je69/3/