Alex5207
Alex5207

Reputation: 484

ReactJs - Correct way to handle state/props

I have three components:

  1. Main (Containing a table component and a button)
  2. Modal component
  3. Form component

The workflow goes like this: A button in main "New X" calls the Modal which opens up with the Form component inside it.

In the above, I have kept the form input as a state of Form (To be able to validate etc.)

Now, I need a new workflow: A double click in the table in Main should open the modal and the form but with the row data entered in the form (To be able to edit the data)

To reuse as much code as possible I wanted to use the same Modal/Form components but pass the row data as props through Modal into component.

As for now, the row data is a state of Main, passed as props to Modal and finally passed as props to Form which then sets it to state.

My question is: Is that the correct way to handle it? In theory I could then have two components having a different state of the data.

Upvotes: 0

Views: 84

Answers (2)

Mosè Raguzzini
Mosè Raguzzini

Reputation: 15821

Yes, it seems the correct way to handle it. React developer's team recommend to keep the state lifted up as much as possible.

For sure you can handle it in different ways but you'll end quite always to lift the state as up as you can.

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138235

Is that the correct way to handle it?

Yes.

In theory I could then have two components having a different state of the data.

No, not really. The Form is the only one that manages the state.

Upvotes: 1

Related Questions