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> 
3
  • Does this answer your question? Adding two numbers concatenates them instead of calculating the sum Commented Jul 6, 2020 at 6: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. Commented Jul 6, 2020 at 6:45
  • @theblackgigant no its a for reactjs code but it has pointed the mistake I have done, Thanks Commented Jul 6, 2020 at 7:01

3 Answers 3

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> 
Sign up to request clarification or add additional context in comments.

Comments

1

Replace the following code

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.