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/
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!
This might help. Make sure you properly set the correct state and handle your updates in your onHandleChange.
const minOffset = 0;
const maxOffset = 60;
class DatePicker extends React.Component {
constructor() {
super();
const thisYear = (new Date()).getFullYear();
this.state = {
thisYear: thisYear,
selectedYear: thisYear
}
}
onHandleChange = (evt) => {
// Handle Change Here
// alert(evt.target.value);
this.setState({ selectedYear: evt.target.value });
};
render() {
const { thisYear, selectedYear } = this.state;
const options = [];
for (let i = minOffset; i <= maxOffset; i++) {
const year = thisYear - i;
options.push(<option value={year}>{year}</option>);
}
return (
<div>
<select value={this.selectedYear} onChange={this.onHandleChange}>
{options}
</select>
</div>
);
}
}
/*
* Render the above component into the div#app
*/
ReactDOM.render(<DatePicker />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></app>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With