Skip to content

Question: Use as controlled or uncontrolled component? #719

Open
@pascalgn

Description

@pascalgn

The terminology might not be the correct one, but what I mean is this: Should we let the modal just display the data it gets as properties or should we keep the state in the modal itself?

I have created an example to demonstrate the two possible ways: https://codesandbox.io/s/xl6o05qr4q

In the first example, <Controlled /> component, the modal has no state itself but instead just displays the values it is given and all updates are handled by the parent component.

In the second example, <Uncontrolled /> component, the modal gets the initial value to display from the parent component, but from then on it keeps the state local and only updates it after it is closed.

The way I see it, the uncontrolled approach would be more suitable in almost all cases, as it behaves as I would expect a modal to behave: Updates are only passed to the caller when the modal is closed. It would be easy to implement some kind of logic where pressing "OK" will pass the updated data, but pressing "Cancel" will not update the data but merely close the modal

On the other hand, passing a constant true to the isOpen prop (<Modal isOpen={true} ... />) feels like I'm using the component in a way it was not intended. However, the {modalOpen && <UncontrolledModal ... />} logic is necessary to make sure React will create a fresh object each time the modal is opened, so I cannot just use the isOpen property in the uncontrolled example.

What do you think about this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions