React JS Sorting and updating Array

Asked
Active3 hr before
Viewed126 times

9 Answers

react
90%

The issue is that you are mutating state. One option is to make a shallow copy of your menu array using the spread operator, and then sorting that array.,Connect and share knowledge within a single location that is structured and easy to search.,Asking for help, clarification, or responding to other answers.

The issue is that you are mutating state. One option is to make a shallow copy of your menu array using the spread operator, and then sorting that array.

this.setState({
   menus: [...this.state.menus].sort(function(a, b) {
      if (a.name < b.name) {
         return -1;
      }
      if (a.name > b.name) {
         return 1;
      }

      return 0;
   })
});
88%

Pretag
 Pretag team - issue, fix, solve, resolve
72%

Hypothetically, when the state will be updated with the new data (sorted array), the component should re-render. To test it we need to define a function that will sort the bands array based on the selected option in the dropdown and call it every time the selected option changes. ,Please, check the full updated code of the tutorial example with nested property sorting here - branch nested-sorting. ,Array is being sorted just fine, as it’s printed in the console, but the array data doesn’t re-render. It only renders when we change the sorted value for the first time.

const bands = [{
      name: 'Nightwish',
      albums: 9,
      members: 6,
      formed_in: 1996,
   },
   {
      name: 'Metallica',
      albums: 10,
      members: 4,
      formed_in: 1981,
   },
   {
      name: 'Nirvana',
      albums: 3,
      members: 3,
      formed_in: 1987,
   },
];
load more v
65%

Sorting data in JavaScript is pretty straightforward, thanks to the built-in array function sort(). It’ll sort arrays of numbers and strings without an extra argument:,Wrapping our code in this function will have huge performance implications for our table sorting!,Table sorting has always been a pretty hard issue to get right. There’s a lot of interactions to keep track of, extensive DOM mutations to do and even intricate sorting algorithms, too. It’s just one of those challenges that are hard to get right. Right?

const ProductsTable = (props) => {
  const { products } = props;
  const [sortedField, setSortedField] = React.useState(null);
  return (
    <table>
      <thead>
        <tr>
          <th>
            <button type="button" onClick={() => setSortedField('name')}>
              Name
            </button>
          </th>
          <th>
            <button type="button" onClick={() => setSortedField('price')}>
              Price
            </button>
          </th>
          <th>
            <button type="button" onClick={() => setSortedField('stock')}>
              In Stock
            </button>
          </th>
        </tr>
      </thead>
      {/* As before */}
    </table>
  );
};
load more v
75%

Bailing out of a state update If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects. (React uses the Object.is comparison algorithm.),Therefore the reference doesn't change in which case React will bail out of rendering.,What I’m trying to explain to him is that he has to change the reference of the value he has to return. But after you’re right the correct way if we use a function is this precisely :):

import React,{useState} from 'react';
const App=()=>{
  const [numbers,setNumbers]=useState([8,6,4,9,7,3,1,2]);

  const sortEvent=()=>{
    setNumbers(num=>num.sort());
  }
  return(<>
    <h1>APP</h1>
    {
      numbers.map(num=><p key={num}>{num}</p>)
    }
    <button onClick={sortEvent}>Sort</button>
    </>
  )
}

export default App;
load more v
40%

As a last resort, you can pass an item’s index in the array as a key. This can work well if the items are never reordered, but reorders will be slow.,Any components below the root will also get unmounted and have their state destroyed. For example, when diffing:,When you use React, at a single point in time you can think of the render() function as creating a tree of React elements. On the next state or props update, that render() function will return a different tree of React elements. React then needs to figure out how to efficiently update the UI to match the most recent tree.

<div>
   <Counter />
</div>

<span>
   <Counter />
</span>
load more v
22%

The following options are supported via the main options object passed to useTable(options),The following options are supported on any Column object passed to the columns options in useTable(),The following properties are available on every Column object returned by the table instance.

Pretag
 Pretag team - issue, fix, solve, resolve
60%

When handling the drag-n-drop sorting, I do all my array manipulation elsewhere and then overwrite the array in state with setState() or with immutable update so the menu will re-render. The problem is, when I try to do this, the list gets re-ordered on render() back to it's original state (or sometimes a random ordering). I'm not sure what is going on, it may be something that I'm doing wrong, but at the same time I've tried everything. So it's looking like something with React that I'm not catching.,I am trying to figure out what is going on with my React component state when re-ordering menu items in a drag-n-drop interface. In my code I have a menu component that is completely drag sortable that gets passed an object with an array of items from the parent components' state.,UPDATE It looks like this was not a problem with react, it was a problem with the drag n drop library that I was using. I have recently integrated with a different library and all the wonky state updating went away.

index.js

var _ = require('lodash');
var Update = require('react-addons-update');

//.....more dnd logic.....//

var myArray = _.cloneDeep($this.state.appMenuData.children);

//get dragged element index
var draggedElemIndex = $this._getNodeIdIndex(el);
var draggedElemObj = myArray[draggedElemIndex];

//element was dragged to the bottom of the list
if(sibling == null){
  var newPos = myArray[myArray.length-1].position;

  myArray[draggedElemIndex].position = newPos;
  myArray[draggedElemIndex].changed = true;

  for(var i = draggedElemIndex+1; i <= myArray.length-1; i++){
    myArray[i].position-=1;
  }

  myArray.sort(function(a, b){
    return a.position-b.position;
  });

  var newData = Update($this.state, {
    appMenuData: {children: {$set: myArray}},
  });

 $this.setState(newData); 
}

//.....more dnd logic.....//

render(){
  <Menu data={this.state.appMenuData} />
}
48%

Using hooks, you can easily apply that to your state array, as shown below. The values can now be used to render a list of paragraph tags using the map function.,At the heart of every app lies its state. No matter the kind of technology you use, your app relies on some sort of state, be it in-memory, on a physical disc, and so on. In React, every component can handle its own state, which might mean clicking a button or the content of a text input. These components are mostly referred to as smart components, whereas components which do not handle state are referred to as dumb components. In this guide, you'll learn how to manipulate state with objects and arrays. Sit tight!,And that's it. You've successfully studied the art of state management with objects and arrays. Tackling state-related issues should now be a breeze for you. If you'd like to chat more about this topic, ping me on Twitter @DesmondNyamador.

1import React from 'react'
2
3class MyComponent extends React.Component {
4	constructor(props){
5		super(props);
6		this.state = { date: new Date(), name: 'Kofi'};	
7	}
8
9	render(){
10		return(
11			<div>
12						<p> Hello {this.state.name} , it is {this.state.toLocaleTimeString()
13						<p>Date: {this.state.date.toLocaleDateString()}
14			</div>
15		)
16	}
17}
load more v

Other "react-undefined" queries related to "React JS Sorting and updating Array"