Skip to content
Advertisement

React and jquery-ui/ui/widgets/sortable: Child component not reorder as expect

I have an array in “State” of parent component called “portfolios”. You can access by using: “this.state.portfolios”.

And a child component called “StockDetailsComponent”.

In parent component, I’m using map function to render child component “StockDetailsComponent” like this:

JavaScript

It’s ok. But when I reorder “this.state.portfolios”, child component re-render not as expected.

Before: portfolios = [“object_stock_symbol_1”, “object_stock_symbol_2”];

After re-order: portfolios = [“object_stock_symbol_2”, “object_stock_symbol_1”];

Parent component looks like as below and lets me explan:

JavaScript

First, I get list Portfolios from the database, assign to “portfolios” of state, shown in the Client. And enable drag/drop to re-order by “enableSortable” function. At this time, it’s working fine.

When I drag to re-order, “this.state.portfolios” changed as expected, I can see in “console.log()” but child component render is wrong. Not as order.

The code is very long, so you only need to pay attention to the following options I tried: Option 1:

JavaScript

result.data.data is data after re-ordered, it’s fine but re-render not work as order.

Option 2: If I clear state by an empty array and set it again like code below, it’s work because child component has been “Unmount” and re-render instead just update like Option 1.

JavaScript

Please help me 🙁 I don’t want to setState and then setState again.

Advertisement

Answer

It looks like that your portfolio data is a complex object which React is not able to determine that has changed. Yoiu can do like below:

You can do like :

JavaScript

or if your portfolio is an object and not an array than you may try below way:

JavaScript

You may try both the ways, and one of them will work out for you depending upon the structure of your portfolio object

Advertisement