S
S
Sss1092021-10-10 18:46:54
React
Sss109, 2021-10-10 18:46:54

Change color to selected. Where is the mistake?

class App extends React.Component {

  constructor(props){
      super(props);
             
      this.state = { color: this.props.colors[0] };
      
      this.changeColor = this.changeColor.bind(this);
  }
  
  changeColor(e){
    this.setState( { color: e.target.value });
  }
 
  render(){          
    return <div>
          <p style={{backgroundColor: this.state.color}}>sample text</p>
          <select onChange={this.changeColor}>
             {this.props.colors.map(c => (<option value={c}>{c}</option>))}
          </select>
          </div>
    }
          
}

ReactDOM.render(
  <App colors={['red', 'green', 'blue']}/>,
  document.getElementById("ex")
);
  
export default App;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexandroppolus, 2021-10-10
@Alexandroppolus

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

A
Aetae, 2021-10-10
@Aetae

There is no problem in the code below:
Look for the error elsewhere.
PS Judging by the text of the error, your array colorsdoes not come in props.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question