DEV Community

raotaohub
raotaohub

Posted on

A easy modal state manager for React!

Hello everyone! Happy to join this community~

This's my first Post!

Next, I will introduce one of my project~ easy-modal-react!

Problem: Modals & the ceremony around managing them

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:

Separate the state between components and Modal

Image description

🚀 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
  • That's the core functionality,Here's the better experience

sure, It's support hooks

import EasyModal, { InnerModalProps } from 'ez-modal-react';

// This step is optional,Depends on whether your modal component requires it
interface IProps extends InnerModalProps<'modal'> {
   age: number;
   name: string;
}

export const InfoModal = EasyModal.create((props: Props) => {
  const modal = useModal<Props /* here */>();
  modal.hide(); // (property) hide: (result: 'modal') => void ts(2554)

  return <Moda>/*...*/</Moda>;
});
Enter fullscreen mode Exit fullscreen mode

🎮 Codesandbox Demo

Demo Link

⌨️ Learn More

ez-modal-react

Top comments (0)