Modal

How to use the modal component

Let's start off by importing and using the Modal component

// import
import Modal from "@wigxel/react-components/libs/cards"



// usage
<Modal 
    name="profile-modal" 
    onClose={() => console.log("Profile Modal closed")}>
    <Message />
    <Buttons />
</Modal>

The Modal component comes with two helper functions. The first:

Dealing with Multiple Modals

When working with mutliple modals in a project the above usage can be exhausting. A more friendly approach will be utilizing the useModal hook and Modal.Provider context.

Modal.useModal

This helper function, just like the naming convention implies is a hook. This hook takes zero arguments and exports the followings:

function UserProfile() {
    const { hide, toggle, show } = Modal.useModal()
    
    return (
        <div>
            ...
            
            <button onClick={() => toggle('profile-modal')}>
                Edit Profile
            </button>
        </div>
    )
}

toggle, show and hide functions all take one argument, which is the name of the modal. From the example above.

Modal.Provider

The <Modal.Provider>context should wrap the root component before calling the Modal.useModal() function. For example:

// App.js
function App() {
    return (
        <Modal.Provider>
            // contains modal
            <UserProfile />
        </Modal.Provider>
    )
}


// UserProfile.js
function UserProfile() {
    const { show } = Modal.useModal()
    
    return (
        <Dashboard>
            <Modal name="profile-modal">
                <Avatar />
                <ProfileForm />
            </Modal>
            
            <button onClick={() => show('profile-modal')}>
                Edit Profile
            </button>
        </Dashboard>
    )
}
Modal.propTypes = {
	// The modal name
	name: t.string,
	// shows or hides the modal 
	show: t.bool,
	// resizes the modal
	size: t.oneOf(["sm", "lg"]),
	// function that gets called when modal closes
	onClose: t.func,
	// indicates the modal needs children
	children: t.node.isRequired,
}

Last updated

Was this helpful?