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.
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>
);
}
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>
);
}
}
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