S
S
Sergey2020-08-15 19:23:45
React
Sergey, 2020-08-15 19:23:45

How to throw different data into one component?

There is a Tabs component that displays lists of tickets with different sorting:
By price
By duration

Accordingly, the tab changes - the sorting changes.
I do this:

return (
    <div className='tabs'>
      <TabsComponent defaultActiveKey='1'>
        <TabPane tab='Самый дешёвый' key='1'>
          <TicketsList
            isLoading={loading}
            tickets={sortByPrices(visibleData)}
          />
        </TabPane>
        <TabPane tab='Самый быстрый' key='2'>
          <TicketsList
            isLoading={loading}
            tickets={sortByDuration(visibleData)}
          />
        </TabPane>
      </TabsComponent>
    </div>
  );
};


TicketsList is a component that receives an array and renders it. I'm trying to pass one array to props, but with different sorting, but changing the tabs I get always sorted by duration.

Where to dig?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wigard, 2020-08-16
@justedoit

const [items, setItems] = useState ([]); // вместо пустого массива массив с данными

function sortByPrices () {
  setItems (items => {
    // сортировка items по цене
    items = items.sort ((a, b) => a > b ? 1 : -1);
    return [...items];
  });
}

function sortByDuration () {
  setItems (items => {
    // сортировка items
    // ...
    return [...items];
  });
}

return (
  <div className='tabs'>
    <TabsComponent defaultActiveKey='1'>
      <TabPane tab='Самый дешёвый' key='1'>
        <TicketsList
          isLoading={loading}
          tickets={items}
        />
      </TabPane>
      <TabPane tab='Самый быстрый' key='2'>
        <TicketsList
          isLoading={loading}
          tickets={items}
        />
      </TabPane>
    </TabsComponent>
  </div>
);

when changing tabs, call sortByPrices and sortByDuration depending on the tab
2 option - store the sort type in state, change the array through useMemo with state in dependencies

0
0xD34F, 2020-08-15
@0xD34F

What do the sortByPrices and sortByDuration methods do? Let me try to guess - they take an array as a parameter, and sort it . If so, then the answer to the question "where to dig" is obvious - dig the basics of js, what data types are, what are their features. Arrays are objects, and when assigning / passing to a function / returning from a function, objects are not copied, references to them are copied. That is, the same array is sorted twice - naturally, the output will display the result of the last sort twice.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question