简体   繁体   中英

Dynamically creating radio buttons using loop in react native

I am creating a sample application in react native. In this app, I have fetched API data in an array. What i need to do is that to create number of radio buttons according to number of elements in array. So i used for loop which executes from index position 0 to array length , but the problem is instead of displaying radio buttons equal to number of elements in array, it is just showing radio button for last element for that particular array.

Below is the code

    var json_response_SelectSegment = await AuthService.GetSegmentDropdown(this.state.machineId,this.state.orderBySegment,this.state.orderByDescendingSegment,this.state.allRecordsSegment);
    console.log("***got Segment Data*******",json_response_SelectSegment.data.data.segmentMainResponse.segmentResponse)
  var Json_respo_Segment=json_response_SelectSegment.data.data.segmentMainResponse.segmentResponse
  console.log("data = ",Json_respo_Segment.length)
  for(i=0;i<Json_respo_Segment.length;i++){
   console.log("**",Json_respo_Segment[i].Segment)
   console.log("**",Json_respo_Segment[i].SegmentId)
   this.state.radio_props_Segment=[{ label: Json_respo_Segment[i].Segment, value: Json_respo_Segment[i].Segment }]
   console.log("Hello : ",this.state.radio_props_Segment)
   
  }

It is showing all the array elements in console.log(for example array contains 4 elements) but it is creating radio button for only last element in UI

Any solution please ?

Try this way

 const radioData = [];

  for(i = 0 ; i < Json_respo_Segment.length ; i++){
   
    radioData.push(
        { label: Json_respo_Segment[i].Segment, 
          value: Json_respo_Segment[i].Segment 
        }
     );   
  }

  const data = [...this.state.radio_props_Segment];
  data.push(radioData);
   
  this.setState({radio_props_Segment: data});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM