Choose a radio button from a React Native FlatList

I am new to React Native and I'm working with the expo-radio-button component.

However, I'm facing an issue where I can't seem to select only one radio button at a time in a flatlist.

When I try to select a single button, it ends up selecting more than one button.

Can someone help me fix this issue? I want to display and select 'yes' or 'no' for each question using radio buttons.

Click here to see the desired output

const myArray = [
  {
    isSignReq: "1",
    sno: "1",
    yesno: "0",
  },
  {
    isSignReq: "1",
    sno: "2",
    yesno: "0",
  },
  {
    isSignReq: "1",
    sno: "3",
    yesno: "0",
  },
];

const [account, setAccount] = useState([]);

const setFormSubmit = (val) => {
  console.log(val);
};

<FlatList
  data={myArray}
  keyExtractor={() => {
    return (
      new Date().getTime().toString() +
      Math.floor(Math.random() * Math.floor(new Date().getTime())).toString()
    );
  }}
  renderItem={(itemData) => {
    return (
      <View style={{ flexDirection: "row", marginVertical: "2%" }}>
        <Text style={styles.data1}>{itemData.item.sno}</Text>
        <Text style={styles.data2}>{itemData.item.name}</Text>
        <View style={{ width: "30%", marginLeft: "1%" }}>
          <RadioButtonGroup
            onSelected={(value) => {
              setFormSubmit(value), setAccount(value);
            }}
            selected={account}
            size={22}
            containerStyle={{ flexDirection: "row" }}
          >
            <RadioButtonItem label={"Yes"} value={itemData.item.isSignReq} />
            <RadioButtonItem label={"No"} value={itemData.item.yesno} />
          </RadioButtonGroup>
        </View>
      </View>
    );
  }}
/>

Answer №1

displayItem = ({item, index}) => {
 .....
<Checkbox
  fillColor={Colors.darkBlue}
  outlineColor={Colors.lightGray}
  animation={'bounceIn'}enter code here
  isChecked={this.state.selectedIndex === index}
  onCheck={() => {this.onCheck(index)}}
/>
}

and switch out onCheck with

onCheck = (index) => {
   this.setState({ selectedIndex: index });
 }

and modify ListView with updatedData prop as ListView requires re-rendering like so:

<ListView
   keyExtractor={this._keyExtractor}
   items={this.state.data}
   displayItem={this.displayItem}
   ItemSeparatorComponent={this.renderSeparator}
   updatedData={this.state}
 />

sample:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using .change(); in JavaScript code with jQuery does not trigger a function

Here we have a generic code example for a jQuery function: $(document).ready(function() { if (something) { // This does something } else if (something else) { // This does something else } else { // And this does somethin ...

Animation using jQuery is functional on most browsers, however, it seems to

After creating an animation to simulate an opening door using jQuery, I discovered that it works perfectly on Firefox 24, Chrome 28, and IE 8. However, Safari presents a problem - the door opens but then the "closed" door reappears at the end of the animat ...

Pressing the icon will trigger a top-sliding dropdown mobile menu to appear

How can I ensure my mobile dropdown menu slides in from the top when the user clicks the "header-downbar-menu" icon and slides out to the top when clicked again? Currently, the button only shows the menu but I am struggling with writing the JavaScript for ...

Integrating an API with a Discord bot using an embedded link in Discord.js

I am currently in the process of creating a bot that can generate and embed links to display manga titles, tags, and other information based on user-input digits. I have been exploring an API called this and I am eager to learn the most effective method ...

Ways to track all requests completed in Nuxt 3

I am looking to create a unique loading page that conceals itself once all requests and static data have been loaded, including static images and libraries. How can I determine when all requests and static data have finished loading? I have attempted the ...

Changing a complex array structure in javascript into a CSV format

I have a complex nested array that I need to convert into a downloadable CSV file. My current approach involves iterating through each array and subarray to build the CSV, but I'm wondering if there's a more efficient method available? Here is a ...

By utilizing jQuery, I am orchestrating the movement of a series of div elements within a container with the simple click of a button

A group of div elements located within a container. When the button is clicked, the train should start moving. <script> $('document').ready(function(){ $("button").click(function(){ $("#train").animate({left: "300px"}, 2000); ...

"Troubleshooting: Click counter in HTML/Javascript unable to function

My latest HTML project is inspired by the "cookie clicker" game, and I'm working on it for a friend. So far, I've managed to get the click counter to function to some extent. Essentially, when you click on the image, the number at the bottom sho ...

Repeat the most recent AJAX request executed

I am currently working on refreshing a specific section of my application which is generated by an AJAX call. I need to target the most recent call that was made and rerun it with the same parameters when a different button is clicked. The data was initial ...

The alignment issue persists in HTML/CSS despite troubleshooting efforts

I am facing a challenge while attempting to center text within a modal window, despite my efforts the text remains uncentered. This is my HTML code: <div ng-init="modalCompassDir()"> <div class="myModal"> <img class='floor ...

Maintain the property characteristics (writable, configurable) following the execution of JSON.parse()

Imagine a scenario where an object is created elsewhere and passed to my module. It could have been generated on the server in node.js, or perhaps in a different module where it was then serialized using JSON.stringify() for transmission (especially if it ...

Building on the functionality of AngularJS, a directive scope can be established to access and modify

Can a directive accept and utilize a parameter as its scope value? For instance: angular .module('app', []) .controller('CTRL', function($scope) { $scope.some_value = { instance1: { key1: 'value11', ...

What about creating a PHP-MySQL voting platform?

I have implemented a PHP-MySQL voting system on my website, similar to YouTube's. I am using AJAX to execute the PHP in newtest.php. The PHP script works fine when tested individually, but when trying to implement the voting functionality through AJAX ...

What's the best way to capture an element screenshot using JavaScript?

I'm working on developing a unique gradient selection application. One of the exciting features I would like to incorporate is the ability for users to save their chosen gradients as digital images (.jpg format) directly onto their computers. When the ...

Is the neglected property being discarded?

First things first, let's talk about my class: class FavoriteFooBar { ... isPreferred: boolean = false; constructor() { this.isPreferred = false; } } Using a utility library called Uniquer, I arrange a list of FavoriteFooBar instances to pr ...

Obtain data from a local JSON file using the http.get() method in Angular 2

I am attempting to utilize the http.get() method in Angular 2 to load a local JSON file. I followed a suggestion from Stack Overflow that involves modifying my app.module.ts: In this example, I have imported the HttpModule and the JsonModule from @angular ...

Using JavaScript to parse JSON response for sending status data through a POST request

I have successfully implemented a PHP code for file uploads. However, I am facing an issue retrieving the JSON response that indicates the upload status. Upon uploading a file via POST method, the response appears as follows: {"html_content":"<p>Fi ...

Add a class to a button in an Angular btn-group if a specific string is found within an

I am currently working on a project where I have multiple buttons that need to toggle an active class when selected in order to change their color. Below is a snippet of what I have: In the array called 'selected', I have: this.selected = [&ap ...

Is it possible to export a constant from within a default function to a different file?

As a newcomer to React and React Native, I am looking to pass a const variable from within a function to another file. I attempted defining it outside of the function and allowing it to be modified inside the function, but encountered an invalid Hook Call ...

Issue: 'class::class()' method is restricted and cannot be accessed within this scope

I have come across a few responses to this issue, but it seems like none of them fully address the problem I am experiencing. This is a simplified version of my code: using namespace std; class classname { private: int foo; classname(); }; class ...