Wednesday, 21 December 2022

How to avoid require cycles between React components that reference each other

I know how to prevent Javascript require cycles in general.

However, I have the special case of two React components that reference each other. One is a Button, the other a Modal component (a Bottom Sheet to be exact). The Button, if pressed, opens the Modal. And sometimes, on the Modal, there is a Button to open the same Modal again (but with different data).

So, my Button component looks like this:

const Button = (props) => {
  ...
  return <TouchableOpacity ...>
    ...
    <Modal ... />
  </TouchableOpacity>
}

And the Modal looks like this:

const Modal = (props) => {
  ...
  return <BottomSheetModal ...>
    ...
    {props.somePropThatRequiresButton && <Button ... />}
  </BottomSheetModal>
}

If Modal and Button are not defined in the same file, this will of course lead to a Require Cycle warning.

Is there a way to prevent the Require Cycle warning without putting those components in the same file?



from How to avoid require cycles between React components that reference each other

No comments:

Post a Comment