Vinod Kumar
Vinod Kumar

Reputation: 337

How to increment a variable inside .map() in react js

I have a react code where it fetches all assessment year and populates in drop down but while displaying I wanted to increment it by one

suppose Assessment year is 2020 I want to show in drop down as FY : 2020-2021

Below code populates in dropdown when I try to increment it appends 1 instead of adding 1

   <select 
      class="form-control"  
      name="selected_FY"
      value="selected_FY" >

     {
         this.state.assessmentyears.map((fin, key) =>{
         return (  
          <option key={key} value={fin.year}>FY: {fin.year}-{fin.year+1}</option> 
          )
          })
       }                                  
 </select> 

Upvotes: 3

Views: 1322

Answers (3)

Clark
Clark

Reputation: 305

The problem point is auto-type conversion in JavaScript, if type of your value is string, then you try to +1, the one will be auto change to string, so the calculation will 20201(if the value is string 2020).

The solution very easy, you just need to change type of your value, if you want to adding 1, you can through Number(), That will change type from string to number, like as Number('2020') + 1 will be 2020.

Upvotes: 0

Pavan Kalyan
Pavan Kalyan

Reputation: 407

Replace the following code

<option key={key} value={fin.year}>FY: {fin.year}-{Number(fin.year)+1}</option> 

Upvotes: 1

DevLoverUmar
DevLoverUmar

Reputation: 13933

The problem is that you are adding '1' to the string value. You should Parse it before incrementing.

<select 
      class="form-control"  
      name="selected_FY"
      value="selected_FY" >

     {
         this.state.assessmentyears.map((fin, key) =>{
         return (  
          <option key={key} value={fin.year}>FY: {fin.year}-{Number(fin.year)+1}</option> 
          )
          })
       }                                  
 </select> 

Upvotes: 2

Related Questions