12

I am trying to show year select box in my component file. I tried a simple for loop but it's giving a syntax error. Here is my code >

render(){
        
    return (
            <div>
                <select value={this.state.exp_year} name="exp_year" className="form-control" onChange={this.handleInputChange} >
                    <option value="">===Select Expiry Year===</option>
                    { for(var i=2017; i<=2050; i++){
                        <option value={i}>{i}</option>
                        }
                    }
                </select>
            </div>                  
            
        );
}   

Please let me know what I am doing wrong.

2 Answers 2

21

Basically, you can't perform straight loops in JSX because it's kind of like asking for a function parameter. What you can do however is you can place an IIFE there which returns an array of options like:

render() {
  return (
    <div>
      <select
        value={this.state.exp_year}
        name="exp_year"
        className="form-control"
        onChange="this.handleInputChange">
        <option value="">===Select Expiry Year===</option>
        {(() => {
          const options = [];

          for (let i = 2017; i <= 2050; i++) {
            options.push(<option value={i}>{i}</option>);
          }

          return options;
        })()}
      </select>
    </div>
  );
}

But that honestly looks messy so you should probably move the loop outside just before returning:

render() {
  const options = [];

  for (let i = 2017; i <= 2050; i++) {
    options.push(<option value={i}>{i}</option>);
  }

  return (
    <div>
      <select
        value={this.state.exp_year}
        name="exp_year"
        className="form-control"
        onChange="this.handleInputChange">
        <option value="">===Select Expiry Year===</option>
        {options}
      </select>
    </div>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

6

Build the options into an array first, then use the array in the JSX code.

class YearComponent {
  render() {
    const options = [];
    for (var i = 2017; i <= 2050; i++) {
      options.push(<option value={i} key={i}>{i}</option>);
    }
    return (
      <div>
        <select
          value={this.state.exp_year}
          name="exp_year"
          className="form-control"
          onChange={this.handleInputChange}
        >
          <option value="">===Select Expiry Year===</option>
          {options}
        </select>
      </div>
    );
  }
}

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.