Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop in return statement of a component in react js

Tags:

reactjs

I am trying to show year select box in component file, I tried simple for loop but its givign 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.

like image 820
Atul Avatar asked Jun 15 '17 07:06

Atul


2 Answers

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>
  );
}
like image 136
dork Avatar answered Sep 22 '22 07:09

dork


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>
    );
  }
}
like image 25
AKX Avatar answered Sep 19 '22 07:09

AKX