Atul
Atul

Reputation: 1711

loop in return statement of a component in react js

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.

Upvotes: 11

Views: 33422

Answers (2)

dork
dork

Reputation: 4578

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>
  );
}

Upvotes: 20

AKX
AKX

Reputation: 169085

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>
    );
  }
}

Upvotes: 6

Related Questions