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.

3
  • 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) Commented Apr 12, 2017 at 11:29
  • looks similar to stackoverflow.com/questions/22876978/loop-inside-react-jsx combine it with: stackoverflow.com/questions/3895478/… Commented Apr 12, 2017 at 11:59
  • @A.Lau Thanks for the tip. I didn't realize that Commented Apr 12, 2017 at 12:29

1 Answer 1

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>
    );
  }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks a lot, bud :)
just one question... What is that key attribute in the <option> tag? What does it do?
while rendering element with looping. you must assign key attribute and it should be unique. based on this key react will manipulate elements here.
is that attribute always necessary when manipulating DOM elements with loops?
Yes, you must add key attribute in loops.
|

Your Answer

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