how to create list of Years in the dropdown using react js JSX

Muhammad Owais picture Muhammad Owais · Apr 5, 2018 · Viewed 11.9k times · Source

I want to create a list of the Years in react JSX

I have a code for the Jquery, please have a look below.

var minOffset = 0, maxOffset = 60; // Change to whatever you want
var thisYear = (new Date()).getFullYear();
var select = $('<select>');

for (var i = minOffset; i <= maxOffset; i++) {
    var year = thisYear - i;
    $('<option>', {value: year, text: year}).appendTo(select);
}

select.appendTo('body');

http://jsfiddle.net/DhpBg/739/

Answer

Prasun picture Prasun · Apr 5, 2018

First, generate all the required years in an array

const year = (new Date()).getFullYear();
const years = Array.from(new Array(20),( val, index) => index + year);

Once you have the years, you can iterate over the array and list it in select control.

Consider following code snippet

constructor(props){
  super(props);
  const year = (new Date()).getFullYear();
  this.years = Array.from(new Array(20),(val, index) => index + year);
}

render() {
  return(
    ...
    <select>
     {
       this.years.map((year, index) => {
         return <option key={`year${index}`} value={year}>{year}</option>
       })
     }
    </select>
    ...
  );
}

Hope this will help!