2

I'm learning react and trying to add a class if a select element holds a value that I want to check against.

class App extends Component {
  test = 'volvo';
  render() {
    return (
      <select style={{marginTop: '30px', marginLeft: '20px'}}>
        <option value="volvo" className={test === 'volvo' ? "selected" : null}>Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
      </select>
    );
  }
}

It's giving me an error where on the line here I have the ternary operator. Can someone tell me the proper way of doing this please? Thanks!

1
  • What error are you getting? Commented Jul 7, 2017 at 11:31

2 Answers 2

2

Since you are accessing a global variable inside the class, you have to use this keyword.

className={this.test === 'volvo' ? "selected" : null}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you! ill accept this as the correct answer when it allows me.
1

In the global execution context (outside of any function), this refers to the global object. Try below code. You have to use this keyword.

class App extends Component {
test = 'volvo';
render() {
return (
  <select style={{marginTop: '30px', marginLeft: '20px'}}>
    <option value="volvo" className={this.test === 'volvo' ? "selected" : null}>Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </select>
  );
 }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.