'How to make a React Modal Component that works in Storybook

Could you help me giving me some ideas of how to implement a ModalBox that works in storybook and algo that could be implement as if it was a library component ?



Solution 1:[1]

I'm not sure if I got it, but the code below might be useful. And in this case, the ModalComponent could come from a UI library.

import { useState } from 'react';
import { ComponentMeta, ComponentStory } from '@storybook/react';
import ModalComponent from '.';

export default {
  title: 'Components/Modal',
  component: ModalComponent
} as ComponentMeta<typeof ModalComponent>;

const Template: ComponentStory<typeof ModalComponent> = (args) => {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <>
      <button onClick={() => setIsOpen(true)}>Click to open modal</button>
      <ModalComponent
        isOpen={isOpen}
        handleClose={() => setIsOpen(false)}
      >
        {args.children}
      </ModalComponent>
    </>
  );
};

export const Modal = Template.bind({});

Modal.args = {
  children: 'Content'
};

Solution 2:[2]

**Modal.jsx**

    import React from 'react'
    import ScrollLock from 'react-scrolllock'
    import KeyHandler, { KEYDOWN } from 'react-key-handler'
    import './Modal.css'
    
    export const Modal = ({ children, onOutsideClick, onEscape }) => (
      <div className='modal-container' onClick={onOutsideClick}>
        <ScrollLock />
        <KeyHandler
          keyEventName={KEYDOWN}
          keyValue='Escape'
          onKeyHandle={onEscape}
        />
        <div className='modal-inner' onClick={event => event.stopPropagation()}>
          {children}
        </div>
      </div>
    )


**Modal.css**

.modal-container {
    background-color: rgba(0, 0, 0, 0.5);
    height: 100vh;
    left: 0;
    position: fixed;
    top: 0;
    width: 100vw;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .modal-inner {
    border-radius: 5px;
    background-color: aliceblue;
    height: 500px;
    width: 600px;
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Washington Braga
Solution 2 Hammad khan