0

I'm a React JS newbie, so as my practice, I'm creating a dynamic birtdate form. My first challenge is listing of years from 1900 to current year (2017) in a selection of birth year, so I used the for loop to make it shorter rather than the horrible way of listing the years one-by-one in the markup. The code below didn't execute successfully, it returned 2017 only.

export default class Items extends Component {
  render() {
    return(
      <div>
        <form>
          <select name='year' className='yearSelect'>
            <option value="">Year</option>
            {
              for(let yearCount = 2017; yearCount >= 1900; yearCount--)
                return <option value={yearCount}>{yearCount}</option>
            }
          </select>
        </form>
      </div>
    );
  }
}

In the console, it threw an error that says: enter image description here

It's the curly brace that bothers me because of the scope so I had to delete the curly brace of the for loop and indent the line inside it.

  • for loops can't "return" stuff. You will need to run that code before the render (putting it into a variable which you then call in that bracket area) – A. L Apr 12 '17 at 11:29
  • looks similar to http://stackoverflow.com/questions/22876978/loop-inside-react-jsx combine it with: http://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-an-array-based-on-suppl – BacLuc Apr 12 '17 at 11:59
  • @A.Lau Thanks for the tip. I didn't realize that –  Apr 12 '17 at 12:29

1 Answers1

1

Update your code like below.

export default class Items extends Component {
  render() {
       let options = [];
         for(let yearCount = 2017; yearCount >= 1900; yearCount--)
             options.push((<option value={yearCount} key={yearCount}>{yearCount}</option>));
    return(
      <div>
        <form>
          <select name='year' className='yearSelect'>
            <option value="">Year</option>
            { options }
          </select>
        </form>
      </div>
    );
  }
}
Irfan Ali
  • 2,238
  • 1
  • 23
  • 22