3

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> 
Vinod Kumar
  • 337
  • 5
  • 19
  • Does this answer your question? [Adding two numbers concatenates them instead of calculating the sum](https://stackoverflow.com/questions/14496531/adding-two-numbers-concatenates-them-instead-of-calculating-the-sum) – Reyno Jul 06 '20 at 06:40
  • 3
    It seems that `fin.year` is `string` instead of `number`. You have to first convert it into a number, e.g. `Number(fin.year) + 1`. – Tsvetan Ganev Jul 06 '20 at 06:45
  • @theblackgigant no its a for reactjs code but it has pointed the mistake I have done, Thanks – Vinod Kumar Jul 06 '20 at 07:01

3 Answers3

2

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> 
DevLoverUmar
  • 11,809
  • 11
  • 68
  • 98
1

Replace the following code

<option key={key} value={fin.year}>FY: {fin.year}-{Number(fin.year)+1}</option> 
Pavan Kalyan
  • 377
  • 1
  • 10
0

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.

Clark
  • 305
  • 1
  • 8