How can I organize data from A to Z in alphabetical order in React Native when the user chooses the A to Z option from the dropdown menu?

I am working on a screen that can display up to 1000 data retrieved from the API.

Here is the image:

https://i.sstatic.net/ErbDD.png

Now, I have implemented a drop-down box where users can select alphabetically from A to Z. After selecting an alphabetical order, the data will be arranged accordingly. How can I achieve this functionality in my code?

I have tried the following code snippet:

// setData(json.results);  <==================it for sorting
      // setData((prevData) => [...prevData, ...newData]);

      // const sorted = [...sortedData, ...newData].sort((a, b) => {
      //   const lastNameA = a.name.first.toLowerCase();
      //   const lastNameB = b.name.first.toLowerCase();
      //   if (lastNameA < lastNameB) return -1;
      //   if (lastNameA > lastNameB) return 1;
      //   return 0;
      // });
      // setSortedData(sorted);

However, it is not functioning as expected when I select the A to Z list in the drop-down box.

Can someone guide me on how to achieve this successfully?

Code:

import {
  StyleSheet,
  Text,
  View,
  Image,
  TextInput,
  FlatList,
  ActivityIndicator,
  SafeAreaView,
} from 'react-native';
import React, { useEffect, useState } from 'react';
import { scale, verticalScale, moderateScale } from 'react-native-size-matters';
import { RFPercentage } from 'react-native-responsive-fontsize';
import SelectDropdown from 'react-native-select-dropdown';

const sortby = ['A to Z', 'Newest', 'Oldest'];

const App = () => {
  // rest of the code...
};

export default App;

// rest of the styles and components...

Answer №1

Here's a code snippet that has worked well for me:

import {
    StyleSheet,
    Text,
    View,
    Image,
    TextInput,
    FlatList,
    ActivityIndicator,
    SafeAreaView,
} from 'react-native';
import React, { useEffect, useState } from 'react';
import { scaleSizes, responsiveFontSizes } from 'react-native-size-matters';
import SelectDropdown from 'react-native-select-dropdown';

const sortingOptions = ['A to Z', 'Newest', 'Oldest'];

const App = () => {
    const [loading, setLoading] = useState(true);
    const [data, setData] = useState([]);
    const [search, setSearch] = useState('');
    const [filteredData, setFilteredData] = useState([]);
    const [masterData, setMasterData] = useState([]);
    const [totalItems, setTotalItems] = useState(0);
    const [searchResultsCount, setSearchResultsCount] = useState(0);

    useEffect(() => {
        fetchData();
    }, []);

    const fetchData = async () => {
        try {
            const response = await fetch('https://randomuser.me/api?results=1000');
            const json = await response.json();
            
            setLoading(false);
            setFilteredData(json.results);
            setMasterData(json.results);
            setTotalItems(json.info.results);
        } catch (error) {
            console.error(error);
        }
    };

    const searchFilterFunction = (text) => {
        if (text) {
            const updatedData = masterData.filter((item) => {
                const itemData = item.name.first ? item.name.first.toUpperCase() : '';
                const searchText = text.toUpperCase();
                return itemData.includes(searchText);
            });
            setFilteredData(updatedData);
            setSearch(text);
            setSearchResultsCount(updatedData.length);
        } else {
            setFilteredData(masterData);
            setSearch(text);
        }
    };

    const renderItem = ({ item }) => (
        <View style={{ padding: 10 }}>
            <Text>Name: {`${item.name.first} ${item.name.last}`}</Text>
            <Text>Email: {item.email}</Text>
            <Text>City: {item.location.city}</Text>
            <Text>State: {item.location.state}</Text>
            <Text>Country: {item.location.country}</Text>
            <Text>Postcode: {item.location.postcode}</Text>
        </View>
    );

    const ItemSeparatorView = () => (
        <View
            style={{
                height: 0.5,
                width: '100%',
                backgroundColor: '#000',
            }}
        />
    );

    return (
        <View>
            {/* UI components and functionality */}
        </View>
    );
};

export default App;

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    // styles for different UI elements like header, input fields, buttons, etc.
});

Make sure to handle all other available options as well! 😉

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

Tips for managing a date picker with JavaScript using the Selenium WebDriver

I have been attempting to scrape a travel website using Selenium Webdriver and Python. While I have successfully set the destination (destino) and place of origin (origem), I am encountering difficulties when trying to select a date. I understand that Ja ...

Angular 5 in conjunction with Keycloak enabling access for non-authenticated users

I have a situation where I need to implement anonymous user access in my app, and for that purpose, I am incorporating the 'keycloak-angular' library along with Angular 5. The documentation instructs me to initialize the application as shown belo ...

Having trouble displaying a cube using three.js even though I have meticulously organized the object-oriented structure of my application

Creating a cube or any other geometric figure with three.js can be crystal clear when your code is simple. However, when trying to incorporate module logic in an OO-style structure for your application, you might encounter some challenges. I have faced sim ...

HTML drop-down menu malfunctioning/missing from view

I am encountering an issue where the drop-down menu is visible, but when I try to make it disappear and then hover over it again to bring it back, it does not reappear. Here is the CSS code I am using: * { margin: 0; padding: 0; } body { back ...

What could be causing the error message 'Why is 'push' property undefined in React Native?

Within my index.ios.js file, I have the following: renderScene(route, navigator){ return <route.component navigator={navigator} {...route.passProps}/> } as well as render() { return ( <Navigator initialRoute={{name: &a ...

Updating an Object in vue.js Upon Click Event to Add a New Value

I currently have a code snippet that looks like the following: arr = [ { val1: a, val2: b }, { val1: a, val2: b }, { val1: a, val2: b } ] <div v-for="single in arr"> <button v-on:click="addSome"></button> </div> When I c ...

Caution: Refs cannot be assigned to function components

I'm currently using the latest version of Next.js to create my blog website, but I keep encountering an error when trying to implement a form. The error message reads as follows: Warning: Function components cannot be given refs. Attempts to access t ...

Utilize custom scrollbar design exclusively for Windows operating system

My goal is to customize the scrollbar style of a div specifically for Windows systems. While most mobile devices have invisible scrollbars that I want to keep hidden, the aesthetics of Mac OS scrollbars are acceptable to me. What I really need is to make t ...

Implement using a variable as a key for an object in a reducer function

I am facing an issue with constructing an object. The string, named "SKU" in this scenario is being passed through action as action.name. Although I have all the necessary data in the reducer function, I need to dynamically replace the hardcoded SKU with ...

Is there a way to remove a pseudo element in CSS using Internet Explorer

I've been struggling to make some pseudo elements work in Internet Explorer, but it seems like I can't get it to function as intended. It's as if IE is ignoring the CSS rules that I have set up for these elements, and it's quite frustr ...

Deactivate a form on the page while another form is being used

My issue involves having two forms on the same web page with identical IDs, and I'm unable to easily change them. Both forms are necessary on the page. When I submit one form, it also submits the other form as blank, resulting in duplicate submission ...

Showing pdf documents without relying on third-party software

Within my Angular application, I have integrated the following snippet into an HTML template: <embed src="../assets/AOK_T2DM.pdf" style="width: 100%;height: 500px" type="application/pdf"> The representation of this code ...

How to selectively load specific scripts in index.html with the use of angular.js

Let me address a problem I'm facing with a large development project. It seems that the current setup does not function properly on Internet Explorer. My idea is to only load files that are compatible and do not generate errors when accessed through I ...

Leverage the Google Drive API for the storage of app-specific data

I'm currently developing a JavaScript application that runs on the client side and need to store a JSON object containing configuration details in a Google Drive Appdata file. Through the Google Drive API, I can successfully check for the file within ...

Display the chosen alternative in a Bootstrap dropdown menu

I am currently facing an issue with the dropdown list in my bootstrap menu. <li class="dropdown"> <a aria-expanded="false" aria-haspopup="true" role="button" data-toggle="dropdown" class="dropdown-toggle" href="#">Chose option<span class="c ...

Setting up node.js for angular - serving static files with connect.static and running unit tests

Currently, I am in the process of setting up a basic node webserver by following a tutorial outlined in Pro AngularJS published by Apress. Node.js along with both the connect and karma modules have been successfully installed on my system. During the ins ...

A specialized identifier for nested objects in a React component

I am currently working with a JSON data structure that looks like this: [ [ { city: x patients: x id: 1 }, { city: y patients: y id: 2 } ], [ { city: x patients: x id: 1 }, { city: y patients: y id: 2 } ...

Adjust the font size to fit within the container

My webpage features a bootstrap 4 container with three columns that adjust on screen sizes above the md breakpoint (col-md-4). Each column contains an img with the class img-fluid, and when hovered over, text description appears. I want this hover text to ...

Is there a way to effectively organize an RSS feed using the .isoDate parameter while ensuring that the feed's elements remain interconnected (such as title and link)?

My goal is to organize the RSS feed by the most recent item while ensuring that each title corresponds correctly with its link. Currently, I am parsing and displaying the feed using the .isoDate property, but I am unsure of the best approach to achieve thi ...

Selenium javascript troubleshooting: encountering problems with splitting strings

Hello, I am new to using selenium and encountering an issue with splitting a string. <tr> <td>storeEval</td> <td>dList = '${StaffAdminEmail}'.split('@'); </td> <td>dsplit1 </td> < ...