DEV Community

raotaohub
raotaohub

Posted on

Why you need modal state management?

Why you need modal state management?

Using modals in React is a bit frustrating.

  1. If we have a complex modal that contains a large amount of form elements.

  2. Or if we have multiple modal components where the next modal component depends on data processed within the previous modal component.

Imagine the issues this could potentially cause.

Why you need modal state management

Problem and Pain Points

When working with modals in React applications, developers often face the following challenges:

  1. Modal Logic Coupling: The logic for opening, closing, and managing the state of modals is typically scattered throughout the components that use them. This can make the codebase harder to understand and maintain.

  2. Code Organization: Mixing modal logic with other component code can lead to a less organized codebase. Developers may struggle to identify and modify modal-related code when needed.

  3. Return Values: When a modal is closed, developers often need to capture the result or user action that occurred within the modal. Managing the return values from modals can be cumbersome and error-prone.

Problem example

function Order() {
    // ...
    const [visible1,setVisible1] = useState(false)
    const [visible2,setVisible2] = useState(false)
    const [visible3,setVisible3] = useState(false)

    const withModalState1 = useState<any>()
    const withModalState2 = useState<any>()
    const withModalState3 = useState<any>()

    // ...omit the method inside Modal

    // ...omit other the method inside Component

    return (
        <main>
            ...
            <Modal1 hidden={visible1}></* ... */></Modal1>
            <Modal2 hidden={visible2}></* ... */></Modal3>
            <Modal3 hidden={visible3}></* ... */></Modal3>
        </main>
    ) 
}
Enter fullscreen mode Exit fullscreen mode

Solution example:

interface IProps extends InnerModalProps<'ok'/* here is return value's type*/> {
   age: number;
   name: string;
 }

export const InfoModal = EasyModal.create(
 (props: Props) => {
  return (
    <Modal
      title="Hello"
      open={props.visible}
      onOk={() => {
       props.hide('ok'); 
      }}
      onCancel={() => {
      props.hide('cancle'); // ts warn "ok"
      }}
    >
      <h1>{props.age}</h1>
    </Modal>
  );
});

// anywhere use it
EasyModal.show(InfoModal, { name: 'foo' }).then((resolve) => {
  console.log(resolve); // if everything is in order. we will get 'ok' or 'cancle'
});
Enter fullscreen mode Exit fullscreen mode

Why use easy-modal-react ?

easy-modal-react is a library for managing modal components' state in React applications.

It provides a solution to decouple the logic of modal components from other components, resulting in more elegant code organization. It is built on the concept of promises and separates the open, close, and other modal states, passing the return values back to the caller through callback resolves after the modal is closed.

Features:

  1. Zero Dependency Utility: easy-modal-react is a standalone utility written in TypeScript that requires no external dependencies.

  2. Context-Based State Control: Utilizing context, easy-modal-react efficiently controls modal states throughout your entire application.

  3. Promise-Based Handling: Enjoy the benefits of promise-based modal management.

  4. Seamless Component Importing: Effortlessly import modal components throughout your app or use specific component IDs, eliminating the need for explicit imports.

  5. Independent Modal Closure: Close modals from within the component itself, independent of the surrounding code. This flexibility allows you to close modals regardless of their location within the application.

  6. easy-modal-react can be seamlessly integrated with any UI library that offers similar modal functionality,such as Material UI, Ant Design...

πŸš€ EasyModal Examples

  1. use EasyModal Provider
import EasyModal from 'ez-modal-react';

function App() {/* ... */}

ReactDOM.render(
    <EasyModal.Provider> // wrap your main Componet
      <App />
    </EasyModal.Provider>
  document.getElementById('root'),
);
Enter fullscreen mode Exit fullscreen mode
  1. create modal
import easyModal from 'ez-modal-react';

const InfoModal = EazyModal.create((props) => (
  <Modal open={props.visible} onOk={props.hide} onCancel={props.hide}></Modal>
));
Enter fullscreen mode Exit fullscreen mode
  1. anywhere use it
import easyModal from 'ez-modal-react';
import InfoModal from './InfoModal';

EasyModal.show(InfoModal, { name: 'foo' }).then((resolve) => {
  console.log(resolve);
});
Enter fullscreen mode Exit fullscreen mode

ez-modal-react-demo - CodeSandbox

click title go to playground-demo.
link:
https://codesandbox.io/p/sandbox/confident-shape-rt7bzr?embed=1

API Overview

Easy Modal React exposes several key functions and interfaces for working with modals:

EasyModal.create

The create function is used to create a higher-order component (HOC) for a modal. It takes a React component as input and returns a modal component with enhanced functionality.

Example usage:

const MyModal = EasyModal.create((props) => {
  // Modal component implementation
    const { hide, remove, resolve, reject, prop1, prop2 } = props
});

// Use MyModal component as a modal in your application
Enter fullscreen mode Exit fullscreen mode

EasyModal.show & EasyModal.hide

The show function is used to open a modal. It takes a modal component and optional props as input and returns a promise that resolves with the result when the modal is closed.

Example usage:

EasyModal.show(MyModal, { prop1: 'value1', prop2: 'value2' }).then((result) => {
  // Handle the result returned from the modal
});
Enter fullscreen mode Exit fullscreen mode

The hide function is used to programmatically close a modal. It takes the modal component as input.

Example usage:

EasyModal.hide(MyModal);
Enter fullscreen mode Exit fullscreen mode

EasyModal.remove

The remove function is used to remove a modal from the modal registry. It takes the modal component as input.

Example usage:

EasyModal.remove(MyModal);
Enter fullscreen mode Exit fullscreen mode

useModal Hook

The useModal hook is used within a modal component to access modal-related functionality, such as hiding or removing the modal, resolving the promise, or accessing modal-specific props.

Example usage:

const MyModal = EasyModal.create(() => {
  const { hide, remove, resolve, reject, prop1, prop2 } = useModal();

  // Use the modal-related functionality and props
});
Enter fullscreen mode Exit fullscreen mode

These are the main functions and hooks provided by Easy Modal React to manage modals in your React applications. By using these APIs, you can easily create, show, hide, and remove modals, as well as handle return values and keep your codebase well-organized.

learn more


Conclusion

Because it is open-source, check out this GitHub repository and feel free to contribute any ideas or feature requests to the project to make it even better!

easy-modal-react aims to address these pain points by providing a clean and organized way to manage modal components' state and handle return values.

Give easy-modal-react a try in your next React

Top comments (0)