What is the best way to arrange map elements in a React application?

I am trying to implement filter buttons for low to high rates and high to low rates, but I am having trouble figuring it out. How can I apply the filter to display the data accordingly?

The data that needs to be filtered is stored in rate.retail_rate.


type Props = {
  shipmentOptions: ShipmentRate[];
  isSelected?: boolean;
  setIsSelected?: Dispatch<SetStateAction<boolean>>;
};

const USPSItems = ({ shipmentOptions, setIsSelected }: Props) => {
  const setSelectedRate = useShipmentRateStore(
    (state) => state.setSelectedRate
  );

  const [selectedItem, setSelectedItem] = useState<number | null>(null);

  const handlePress = (rate: ShipmentRate, index: number) => {
    setSelectedItem(index);
    setSelectedRate(rate);
    setIsSelected(true);
  };

  return (
    <>
      <ShipmentRatesContainer>
        {shipmentOptions &&
          shipmentOptions.map((rate: ShipmentRate, index) => (
            <ClickableItem key={index} onClick={() => handlePress(rate, index)}>
              <PackagesActiveItem
                key={index}
                index={index}
                isSelected={index === selectedItem}
              >
                <PackagesItemIcon>
                  <SVGCustomIcon name="USPSLogo" />
                </PackagesItemIcon>
                <div style={{ display: "flex", flexDirection: "column" }}>
                  <PackagesItemLocation>{rate.carrier}</PackagesItemLocation>
                  <PackagesItemService>{rate.service}</PackagesItemService>
                </div>
                <PackagesItemRight>
                  <PackagesItemRightText>
                    ${rate.retail_rate}
                  </PackagesItemRightText>
                </PackagesItemRight>
                <USPSItemBottomText>
                  Estimated to arrive{" "}
                  {rate.est_delivery_days
                    ? "in " + rate.est_delivery_days + " business days"
                    : "within the next day"}
                </USPSItemBottomText>
              </PackagesActiveItem>
            </ClickableItem>
          ))}
      </ShipmentRatesContainer>
    </>
  );
};

Answer №1

If you are interested in learning more about sorting arrays in JavaScript, I recommend checking out this helpful documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#sorting_with_map I have extracted the following code snippet from the provided link:

    // Define an array that needs to be sorted
    const data = ['delta', 'alpha', 'charlie', 'bravo'];
    
    // Create a temporary array to store objects with position and sort value
    const mapped = data.map((value, index) => {
      return { index, value: performTimeConsumingOperation(value) };
    })
    
    // Sort the mapped array based on the reduced values
    mapped.sort((first, second) => {
      if (first.value > second.value) {
        return 1;
      }
      if (first.value < second.value) {
        return -1;
      }
      return 0;
    });
    
    // Map back to original order
    const result = mapped.map((object) => data[object.index]);

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

Intercommunication of variables among components

My scenario involves two components, namely App and SomeComponent. I'm aiming to access a variable in App from SomeComponent. App: import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css& ...

Title bar / Popup within the confines of a child container

My dilemma arises from my desire to showcase a mobile phone replica on the webpage using components from Material UI, such as AppBar and Dialog. However, these components do not remain within the confines of the phone container; instead, they extend to the ...

"Learn how to dynamically update the state in React with the useState hook by clicking a button

When working with React, I often find myself needing to update the state using the useState hook. const [CombinedData, setCombinedData] = useState([{ makeTeacher:'', makeSub:'' }]) *This is where I define my hook* {Teacher && ...

Activate TypeScript EMCAScript 6 support for Cordova projects in Visual Studio

I am interested in utilizing the async/await feature of TypeScript in my VS2015 Cordova project. I have updated "target": "es6" in tsconfig.json Although there are no errors shown in intellisense, I encounter the following error while building the project ...

What is the best way to implement a proxy in a React build?

this is the specific api request I need to make http://localhost:3000/api/getUserName however, I am using a proxy in my package.json. After attempting to build the application, the call now goes to http://localhost:5000/api/getUserName Since I am ...

Can you explain how to utilize theme values in CSS within Mui?

Working on my React app with mui themes, I have the following in index.js: let theme = createTheme({ palette: { primary: { main: "#00aaa0", contrastText: '#fcf4d9', }, secondary: { main: "#D55B3E&quo ...

React - Incorrect components experiencing style changes due to setTimeout

Check out the code snippet here: https://jsfiddle.net/69z2wepo/204131/ A main component displays two 'notifications' each with different disappearance timings. class Page extends React.Component { constructor(props) { super(props); t ...

Difficulty in connecting React to Node.js with the use of axios

Recently, I embarked on a project using React and Node to create an app that allows users to add people data to a database. The frontend is built with React and can be accessed at localhost:3000, while the backend, developed with Node, runs on localhost:33 ...

Encountering an "invalid query parameter" error when making a find request with FeatherJS and ReactJS

Adding $show:true to the data below results in an error when making the find request. However, when I remove $show:true, everything works perfectly with no errors. The error message states: Invalid query parameter $show. I have attempted using differe ...

What is the best way to show the previous month along with the year?

I need help with manipulating a date in my code. I have stored the date Nov. 1, 2020 in the variable fiscalYearStart and want to output Oct. 2020. However, when I wrote a function to achieve this, I encountered an error message: ERROR TypeError: fiscalYear ...

React Error: Invalid Element Type with Named Exports

I've been diving into the world of React hooks and functions, working on three different files. First, there's one that establishes a context called SummaryContext. The second file contains a class component that consumes this context named WikiS ...

Tips for perfectly aligning all elements in a row within a card design

Hi there, I'm trying to figure out how to align the content of this card in a single row instead of stacked on top of each other. Here's the code snippet: <div class="container"> <form onSubmit={submitHandler}> ...

Using ReactJS to transform my unique array into an object before appending it to a list

Here is the array I am working with: [{…}] 0: {id: 2, createdAt: "2021-06-11T10:13:46.814Z", exchangedAt: "2021-06-11T08:04:11.415Z", imageUrl: "url", user: "user", …} 1: .... 2: .... 3: .... .... length: 5 __pro ...

Experience the innovative feature of React Splide Carousel where a peek of the next image is shown until you reach

My current challenge arises when I reach the last slide in the slider. I am trying to prevent it from looping and instead stop with no extra space or any other images peeking out. To address this, I have utilized the padding: '5%' option, which ...

"Encountered a 'Network Error' while using Axios and DjangoREST, but pleasantly surprised when the request ultimately succeeds

So, I'm currently using ReactJS and DjangoRESTframework for my app development. When I test the API endpoints with Postman, everything works perfectly (e.g. 127.0.0.1:8000/api/users/ GET request). However, when I try to make the same requests in Rea ...

Developing a secure user authentication process using React.JS and Node.JS

I'm looking to incorporate a login system within the MERN stack that includes three types of logins: 1. Admin login 2. Student Login 3. Faculty Login The admin login will come with default credentials (admin & admin@123), which can be changed if ...

Custom Typescript type that runs concurrently with the base type is disregarded

Assumption: When creating a custom type that mirrors an existing type, the expectation is for variables assigned to that type to maintain it and not default back to the base type. In the function f provided below, the expected return type should be Dog ins ...

Distribute the capabilities of the class

Is there a way to transfer the functionalities of a class into another object? Let's consider this example: class FooBar { private service: MyService; constructor(svc: MyService) { this.service = svc; } public foo(): string { ...

Error: The React styleguidist encountered a ReferenceError due to the absence of the defined

After integrating react styleguidist into my project, I encountered an issue when running npm run styleguidist. The error message states: ReferenceError: process is not defined Here is a snippet from my styleguide.config.js file: module.exports = { ti ...

The UseEffect hook can be triggered multiple times after updating the state

How can I prevent the useEffect hook in my child component from being called twice when updating the state of the parent component? Below is a snippet of code from the child component. useEffect = () => { const flag = someApi; setStateOfParent(flag), ...