Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutating props in React

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?

like image 203
Neil Middleton Avatar asked Mar 31 '15 13:03

Neil Middleton


People also ask

Can props be mutated in React?

One can not change props directly. One can only update state by using setState() .

Can you mutate props?

Props are overwritten when re-rendering When Vue re-renders your component — which happens every time something changes — it will overwrite any changes you have made to your props. This means that even if you try to mutate the prop locally, Vue will keep overwriting those changes.

What is mutating in React?

To run a mutation, you first call useMutation within a React component and pass it a GraphQL string that represents the mutation. When your component renders, useMutation returns a tuple that includes: A mutate function that you can call at any time to execute the mutation.

What is mutable vs immutable in React?

A mutable object is an object whose state can be modified after it is created. Immutables are the objects whose state cannot be changed once the object is created.


1 Answers

Props 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
like image 179
al8anp Avatar answered Sep 21 '22 10:09

al8anp