I have a React component which receives an array or objects via props
. Something I would like to do is have an event re-order these props. However, it seems that React re-rendering only occurs when state
changes.
Right now I have the ordering handled in the parent object and pass the method to handle the ordering through as a prop, but ideally I want the component responsible for rendering these objects to also handle the ordering.
Chucking props
into state
seems bad, but what's the best thing to do here?
I have a React component which receives an array or objects via props
. Something I would like to do is have an event re-order these props. However, it seems that React re-rendering only occurs when state
changes.
Right now I have the ordering handled in the parent object and pass the method to handle the ordering through as a prop, but ideally I want the component responsible for rendering these objects to also handle the ordering.
Chucking props
into state
seems bad, but what's the best thing to do here?
- As I see you have two options. Either "chuck" them into state and then manipulate the state. The other option is to add some flux architecture to the project, then you could fire an action when a re-arrange event happens and the component which passes the props could do the re-arrange when it gets the event and then pass the newly arranged props. – magnudae Commented Mar 31, 2015 at 13:18
- 1 Why not just have the parent do the sorting? Changing the properties of a child component will cause it to re-render: jsfiddle.net/wiredprairie/re7q4c57 – WiredPrairie Commented Mar 31, 2015 at 13:49
2 Answers
Reset to default 11Props are immutable, but in your case it seems that your data does not change, only the sort order changes, so you can:
- keep your data and sort functions as props
- store your sort order in state
- maybe use
getInitialState
to return the default sort order - when sort order is changed, state is set so re-render happens
As i understand React needs to change the state to trigger the render. If you want to keep the sort logic attached to you component you have to create a copy of the array.
getInitialState: function () {
return {
items: this.props.items.slice(0)
};
},
As implemented here.