### React Modal General Usage with All Props
Source: https://github.com/reactjs/react-modal/blob/master/docs/index.md
Demonstrates the general usage of the React Modal component, showcasing all available props and their default or example values. This includes controlling visibility, managing focus, styling, and accessibility attributes.
```jsx
import ReactModal from 'react-modal';
document.body
/* Function that will be called to get the parent element
that the modal will be attached to. */}
aria={
{
labelledby: "heading",
describedby: "full_description"
}
/* Additional aria attributes (optional). */}
data={
{ background: "green" }
/* Additional data attributes (optional). */}
testId={
""
/* String testId that renders a data-testid attribute in the DOM,
useful for testing. */}
overlayRef={
setOverlayRef
/* Overlay ref callback. */}
contentRef={
setContentRef
/* Content ref callback. */}
overlayElement={
(props, contentElement) =>
```
--------------------------------
### Install react-modal using npm or yarn
Source: https://github.com/reactjs/react-modal/blob/master/README.md
Instructions for installing the react-modal package using either npm or yarn package managers. This is the standard way to add the library to a React project.
```bash
$ npm install --save react-modal
$ yarn add react-modal
```
--------------------------------
### Basic React Modal Implementation with Custom Styles
Source: https://github.com/reactjs/react-modal/blob/master/README.md
A comprehensive example demonstrating how to implement a modal dialog using react-modal in a React application. It includes setting up state for modal visibility, defining custom styles, and handling modal open/close events. Accessibility is addressed by setting the app element.
```jsx
import React from 'react';
import ReactDOM from 'react-dom';
import Modal from 'react-modal';
const customStyles = {
content: {
top: '50%',
left: '50%',
right: 'auto',
bottom: 'auto',
marginRight: '-50%',
transform: 'translate(-50%, -50%)',
},
};
// Make sure to bind modal to your appElement (https://reactcommunity.org/react-modal/accessibility/)
Modal.setAppElement('#yourAppElement');
function App() {
let subtitle;
const [modalIsOpen, setIsOpen] = React.useState(false);
function openModal() {
setIsOpen(true);
}
function afterOpenModal() {
// references are now sync'd and can be accessed.
subtitle.style.color = '#f00';
}
function closeModal() {
setIsOpen(false);
}
return (
(subtitle = _subtitle)}>Hello
I am a modal
);
}
ReactDOM.render(, appElement);
```
--------------------------------
### Applying Styles to React Modal
Source: https://github.com/reactjs/react-modal/blob/master/docs/styles/index.md
Demonstrates how to pass inline styles to the `Modal` component via the `style` prop. These styles are merged with default styles defined in `Modal.defaultStyles`. The example shows custom styles for both the overlay and content elements.
```jsx
```
--------------------------------
### Implement React-Modal Lifecycle Callbacks
Source: https://context7.com/reactjs/react-modal/llms.txt
Utilize `onAfterOpen` and `onAfterClose` callbacks in react-modal to execute code after the modal opens or closes. The `onAfterOpen` callback receives an object containing references to the overlay and content elements, useful for focusing elements or performing setup.
```jsx
import React, { useState, useRef } from 'react';
import Modal from 'react-modal';
Modal.setAppElement('#root');
function ModalWithCallbacks() {
const [isOpen, setIsOpen] = useState(false);
const inputRef = useRef(null);
function handleAfterOpen({ overlayEl, contentEl }) {
console.log('Modal opened');
console.log('Overlay element:', overlayEl);
console.log('Content element:', contentEl);
// Focus the input after modal opens
if (inputRef.current) {
inputRef.current.focus();
}
}
function handleAfterClose() {
console.log('Modal closed');
// Clean up or reset state
}
return (
setIsOpen(false)}
contentLabel="Modal with Callbacks"
>
Enter Your Name
);
}
```
--------------------------------
### Customize Overlay and Content Elements in React Modal
Source: https://context7.com/reactjs/react-modal/llms.txt
Customize the rendered overlay and content elements of a react-modal using the `overlayElement` and `contentElement` props. This allows for complete control over the modal's structure and styling while maintaining its core functionality. Ensure the `react-modal` library is installed and imported.
```jsx
import React, { useState } from 'react';
import Modal from 'react-modal';
Modal.setAppElement('#root');
function CustomElementModal() {
const [isOpen, setIsOpen] = useState(false);
return (
setIsOpen(false)}
overlayElement={(props, contentElement) => (
);
}
```
--------------------------------
### Accessing Modal Content in Tests
Source: https://github.com/reactjs/react-modal/blob/master/docs/testing/index.md
When testing React Modal components with React Test Utils, you must set `isOpen={true}` for the modal to render. To interact with the modal's content, use the `.portal` property to get a DOM node handle. This is crucial for making assertions on the modal's children or its internal structure.
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import Modal from 'react-modal';
// Assume Modal is rendered and available as renderedModal
// For example:
// const renderedModal = TestUtils.renderIntoDocument(
Modal Content
);
// Accessing the DOM node of the modal's portal
const modalNode = ReactDOM.findDOMNode(renderedModal.portal);
// Or using TestUtils to find components within the modal's portal
const modalComponents = TestUtils.scryRenderedDOMComponentsWithClass(Modal.portal, 'my-modal-class');
```
--------------------------------
### CSS for Body and HTML Open Classes
Source: https://github.com/reactjs/react-modal/blob/master/docs/styles/classes.md
Example CSS rules to disable overflow for elements with the `ReactModal__Body--open` and `ReactModal__Html--open` classes. This is commonly used to prevent body scrolling when a modal is active.
```css
.ReactModal__Body--open,
.ReactModal__Html--open {
overflow: hidden;
}
```
--------------------------------
### Basic Modal Usage in React
Source: https://context7.com/reactjs/react-modal/llms.txt
Demonstrates the fundamental usage of the Modal component. It requires `isOpen` to control visibility and `onRequestClose` to handle closing events. `Modal.setAppElement` is crucial for accessibility.
```jsx
import React, { useState } from 'react';
import Modal from 'react-modal';
// Set the app element for accessibility (required)
Modal.setAppElement('#root');
function App() {
const [modalIsOpen, setIsOpen] = useState(false);
function openModal() {
setIsOpen(true);
}
function closeModal() {
setIsOpen(false);
}
return (
Modal Title
This is the modal content.
);
}
```
--------------------------------
### Testing Modals with React Testing Library
Source: https://context7.com/reactjs/react-modal/llms.txt
When testing modals using tools like React Testing Library, set `isOpen={true}` to ensure the modal is rendered and visible. Utilize the `testId` prop for reliable element selection within your tests. Remember to set the app element for accessibility using `Modal.setAppElement(document.body)`.
```jsx
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import Modal from 'react-modal';
Modal.setAppElement(document.body);
function TestableModal({ isOpen, onClose }) {
return (
Test Modal
);
}
// Test example:
// test('modal opens and closes', () => {
// const handleClose = jest.fn();
// render();
//
// expect(screen.getByText('Test Modal')).toBeInTheDocument();
//
// fireEvent.click(screen.getByText('Close'));
// expect(handleClose).toHaveBeenCalled();
// });
```
--------------------------------
### Configure React-Modal Transition Animations
Source: https://context7.com/reactjs/react-modal/llms.txt
Configure CSS transitions for react-modal using the `closeTimeoutMS` prop and transition class names. The modal automatically adds `--after-open` and `--before-close` class suffixes during transitions, allowing for custom styling of overlay and content elements.
```jsx
import React, { useState } from 'react';
import Modal from 'react-modal';
Modal.setAppElement('#root');
function AnimatedModal() {
const [isOpen, setIsOpen] = useState(false);
return (
setIsOpen(false)}
closeTimeoutMS={200}
className={{
base: 'modal-content',
afterOpen: 'modal-content--after-open',
beforeClose: 'modal-content--before-close'
}}
overlayClassName={{
base: 'modal-overlay',
afterOpen: 'modal-overlay--after-open',
beforeClose: 'modal-overlay--before-close'
}}
contentLabel="Animated Modal"
>
Animated Modal
);
}
// CSS for fade transition:
// .modal-overlay {
// opacity: 0;
// transition: opacity 200ms ease-in-out;
// }
// .modal-overlay--after-open {
// opacity: 1;
// }
// .modal-overlay--before-close {
// opacity: 0;
// }
```
--------------------------------
### Include react-modal via CDN for React Apps
Source: https://github.com/reactjs/react-modal/blob/master/README.md
Steps to include the react-modal library in a React application using a CDN link. This method is suitable for projects that do not use a module bundler like Webpack or Parcel.
```html
```
--------------------------------
### Manage Multiple Independent Modals in React
Source: https://context7.com/reactjs/react-modal/llms.txt
Control multiple independent modals in a React application by managing the `isOpen` state for each modal separately. This approach allows for complex user flows where different modals can be opened and closed without interfering with each other. Import `React`, `useState`, and `Modal` from 'react-modal'.
```jsx
import React, { useState } from 'react';
import Modal from 'react-modal';
Modal.setAppElement('#root');
function MultipleModals() {
const [modal1Open, setModal1Open] = useState(false);
const [modal2Open, setModal2Open] = useState(false);
return (
setModal1Open(false)}
contentLabel="Modal 1"
>
First Modal
This is the first modal.
setModal2Open(false)}
contentLabel="Modal 2"
>
Second Modal
This modal can be opened independently or from Modal 1.
);
}
```
--------------------------------
### Configure App Element for Accessibility
Source: https://context7.com/reactjs/react-modal/llms.txt
Configures the root application element for react-modal's accessibility features, such as hiding the main app content from screen readers when a modal is active. Supports CSS selectors, DOM elements, or NodeLists.
```jsx
import Modal from 'react-modal';
// Using a CSS selector
Modal.setAppElement('#root');
// Using a DOM element directly
Modal.setAppElement(document.getElementById('root'));
// Using multiple elements
Modal.setAppElement(document.querySelectorAll('.app-container'));
```
--------------------------------
### Styling Modal Content and Overlay with CSS Classes
Source: https://github.com/reactjs/react-modal/blob/master/docs/styles/classes.md
Configure the modal content and overlay using CSS classes via `className` and `overlayClassName` props. These props can accept a single class name string or an object with `base`, `afterOpen`, and `beforeClose` keys for more granular control. Specifying these props overrides default styles.
```javascript
import React from 'react';
import Modal from 'react-modal';
function MyModal() {
const customStyles = {
content: {
base: 'my-custom-content-base-class',
afterOpen: 'my-custom-content-after-open-class',
beforeClose: 'my-custom-content-before-close-class'
},
overlay: {
base: 'my-custom-overlay-base-class',
afterOpen: 'my-custom-overlay-after-open-class',
beforeClose: 'my-custom-overlay-before-close-class'
}
};
return (
Modal Content
);
}
```
--------------------------------
### Correctly Toggle React Modal Visibility in React 16
Source: https://github.com/reactjs/react-modal/blob/master/docs/styles/transitions.md
This JavaScript code illustrates the recommended way to manage the visibility of a React Modal in React 16. Instead of conditionally rendering the `` component, you should use the `isOpen` prop to control its display. This ensures that the modal's unmounting process, especially concerning transitions, functions correctly.
```javascript
{
this.toggleModal()}
>
Add modal content here
}
```
--------------------------------
### Accessing DOM Nodes with Refs in React Modal (JSX)
Source: https://github.com/reactjs/react-modal/blob/master/docs/index.md
This snippet illustrates how to use the `overlayRef` and `contentRef` props provided by the `react-modal` library. These props accept callback functions that receive the respective DOM node as an argument, allowing direct manipulation or inspection of the overlay and modal content elements. This is useful for integrating with other libraries or performing imperative DOM operations.
```jsx
(this.overlayRef = node)}
contentRef={node => (this.contentRef = node)}>
Modal Content.
```
--------------------------------
### Configure React-Modal Close Behavior
Source: https://context7.com/reactjs/react-modal/llms.txt
Control the closing behavior of the modal using props like `shouldCloseOnOverlayClick`, `shouldCloseOnEsc`, and `shouldReturnFocusAfterClose`. These props allow fine-tuning user interactions for closing the modal.
```jsx
import React, { useState } from 'react';
import Modal from 'react-modal';
Modal.setAppElement('#root');
function ControlledCloseModal() {
const [isOpen, setIsOpen] = useState(false);
return (
setIsOpen(false)}
shouldCloseOnOverlayClick={true} // Close when clicking overlay (default: true)
shouldCloseOnEsc={true} // Close on Escape key (default: true)
shouldReturnFocusAfterClose={true} // Return focus to trigger element (default: true)
shouldFocusAfterRender={true} // Focus modal content after render (default: true)
preventScroll={false} // Prevent scroll when focusing (default: false)
contentLabel="Controlled Close Modal"
>
Controlled Close Behavior
Press Escape or click the overlay to close.
);
}
```
--------------------------------
### Configure React Modal Transition Timeout
Source: https://github.com/reactjs/react-modal/blob/master/docs/styles/transitions.md
This JavaScript snippet demonstrates how to set the `closeTimeoutMS` prop on the `` component. This prop, expressed in milliseconds, must match the transition duration defined in your CSS or inline styles to ensure the modal closes smoothly after the animation completes.
```javascript
```
--------------------------------
### Custom Inline Styles for Modal
Source: https://context7.com/reactjs/react-modal/llms.txt
Applies custom inline styles to the modal overlay and content. The `style` prop accepts an object with `overlay` and `content` keys, which are merged with default styles for appearance customization.
```jsx
import React, { useState } from 'react';
import Modal from 'react-modal';
Modal.setAppElement('#root');
const customStyles = {
overlay: {
backgroundColor: 'rgba(0, 0, 0, 0.75)',
zIndex: 1000
},
content: {
top: '50%',
left: '50%',
right: 'auto',
bottom: 'auto',
marginRight: '-50%',
transform: 'translate(-50%, -50%)',
padding: '40px',
borderRadius: '8px',
maxWidth: '500px',
width: '90%'
}
};
function CenteredModal() {
const [isOpen, setIsOpen] = useState(false);
return (
This modal is centered on the screen with custom styling.
);
}
```
--------------------------------
### Access DOM Elements with Refs in React-Modal
Source: https://context7.com/reactjs/react-modal/llms.txt
Utilize `overlayRef` and `contentRef` callback props to obtain direct references to the overlay and content DOM elements within a react-modal. This allows for custom manipulation or measurement of these elements after they are mounted.
```jsx
import React, { useState, useCallback } from 'react';
import Modal from 'react-modal';
Modal.setAppElement('#root');
function ModalWithRefs() {
const [isOpen, setIsOpen] = useState(false);
const handleOverlayRef = useCallback((node) => {
if (node) {
console.log('Overlay element:', node);
// Custom overlay manipulation
}
}, []);
const handleContentRef = useCallback((node) => {
if (node) {
console.log('Content element:', node);
// Measure content, scroll to position, etc.
}
}, []);
return (
setIsOpen(false)}
overlayRef={handleOverlayRef}
contentRef={handleContentRef}
contentLabel="Modal with Refs"
>
Modal with DOM Refs
);
}
```
--------------------------------
### Mount React-Modal to a Custom Parent Element
Source: https://context7.com/reactjs/react-modal/llms.txt
The `parentSelector` prop enables mounting the modal's portal to a specific DOM element instead of the default `document.body`. This is useful for isolating modals within certain parts of the application's DOM structure.
```jsx
import React, { useState } from 'react';
import Modal from 'react-modal';
Modal.setAppElement('#root');
function ModalWithCustomParent() {
const [isOpen, setIsOpen] = useState(false);
return (
This modal is mounted inside #modal-container instead of body.
);
}
```
--------------------------------
### Implement Fade Transition with CSS Classes for React Modal
Source: https://github.com/reactjs/react-modal/blob/master/docs/styles/transitions.md
This CSS code defines styles for the React Modal overlay to create a fade-in and fade-out transition effect. It targets the `.ReactModal__Overlay` class and its states for opening and closing. Ensure the `transition` duration matches the `closeTimeoutMS` prop for proper synchronization.
```css
.ReactModal__Overlay {
opacity: 0;
transition: opacity 2000ms ease-in-out;
}
.ReactModal__Overlay--after-open{
opacity: 1;
}
.ReactModal__Overlay--before-close{
opacity: 0;
}
```
--------------------------------
### Modify Default Styles Globally in React Modal
Source: https://context7.com/reactjs/react-modal/llms.txt
Globally customize the default styles for all react-modal instances by modifying the `Modal.defaultStyles` object before rendering any modals. This allows for consistent styling across your application's modals. Ensure the `react-modal` library is imported.
```javascript
import Modal from 'react-modal';
// Customize default styles globally
Modal.defaultStyles = {
overlay: {
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(0, 0, 0, 0.85)'
},
content: {
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
border: 'none',
background: '#fff',
overflow: 'auto',
WebkitOverflowScrolling: 'touch',
borderRadius: '8px',
outline: 'none',
padding: '30px',
maxWidth: '600px',
width: '90%'
}
};
// All modals will now use these default styles
Modal.setAppElement('#root');
```
--------------------------------
### React Modal Custom Parent Node Configuration
Source: https://github.com/reactjs/react-modal/blob/master/docs/index.md
Configures the React Modal to append its portal to a custom parent DOM element instead of the default document body. This is achieved using the `parentSelector` prop, which accepts a function returning the desired parent element.
```jsx
document.querySelector('#root')}>
Modal Content.
```
--------------------------------
### Applying Class to the Entire Portal
Source: https://github.com/reactjs/react-modal/blob/master/docs/styles/classes.md
Use the `portalClassName` prop to apply a specific CSS class to the root element of the entire modal portal. This allows for styling the outermost container of the modal, which by default has no specific styles applied.
```javascript
import React from 'react';
import Modal from 'react-modal';
function MyModal() {
return (
Modal Content
);
}
```
--------------------------------
### CSS Class-Based Styling for Modal
Source: https://context7.com/reactjs/react-modal/llms.txt
Applies custom styling to the modal and its overlay using CSS classes via the `className` and `overlayClassName` props. This method disables default styles, allowing full control through external stylesheets.
```jsx
import React, { useState } from 'react';
import Modal from 'react-modal';
Modal.setAppElement('#root');
function StyledModal() {
const [isOpen, setIsOpen] = useState(false);
return (
setIsOpen(false)}
className="custom-modal"
overlayClassName="custom-overlay"
contentLabel="Styled Modal"
>
CSS Styled Modal
);
}
// CSS (in your stylesheet):
// .custom-overlay {
// position: fixed;
// top: 0;
// left: 0;
// right: 0;
// bottom: 0;
// background-color: rgba(0, 0, 0, 0.75);
// }
// .custom-modal {
// position: absolute;
// top: 50%;
// left: 50%;
// transform: translate(-50%, -50%);
// background: white;
// padding: 20px;
// border-radius: 4px;
// outline: none;
// }
```
--------------------------------
### Add ARIA Attributes to React-Modal for Accessibility
Source: https://context7.com/reactjs/react-modal/llms.txt
Enhance react-modal accessibility by using the `aria` prop to pass additional ARIA attributes and `contentLabel` for screen reader labels. This ensures that assistive technologies can properly interpret and interact with the modal content.
```jsx
import React, { useState } from 'react';
import Modal from 'react-modal';
Modal.setAppElement('#root');
function AccessibleModal() {
const [isOpen, setIsOpen] = useState(false);
return (
setIsOpen(false)}
aria={{
labelledby: 'modal-heading',
describedby: 'modal-description'
}}
role="alertdialog"
>
Confirm Action
Are you sure you want to delete this item? This action cannot be undone.
);
}
```
--------------------------------
### Manage Body and HTML Classes with React-Modal
Source: https://context7.com/reactjs/react-modal/llms.txt
The `bodyOpenClassName` and `htmlOpenClassName` props allow you to add specific CSS classes to the `` and `` elements, respectively, when the modal is open. This is commonly used to prevent background scrolling.
```jsx
import React, { useState } from 'react';
import Modal from 'react-modal';
Modal.setAppElement('#root');
function ModalWithBodyClass() {
const [isOpen, setIsOpen] = useState(false);
return (
setIsOpen(false)}
bodyOpenClassName="modal-open no-scroll"
htmlOpenClassName="modal-open-html"
contentLabel="Modal with Body Class"
>
Modal Content
The body now has 'modal-open no-scroll' classes applied.
);
}
// CSS to prevent scrolling:
// .modal-open {
// overflow: hidden;
// }
// .modal-open-html {
// overflow: hidden;
// }
```
--------------------------------
### Controlling Body and HTML Classes with react-modal
Source: https://github.com/reactjs/react-modal/blob/master/docs/styles/classes.md
Manage CSS classes applied to `document.body` and the `` tag when a modal is open using `bodyOpenClassName` and `htmlOpenClassName` props. These props accept constant strings for class names, allowing for global styling adjustments like disabling scroll. Setting `bodyOpenClassName` to `null` prevents any body class from being added.
```javascript
import React from 'react';
import Modal from 'react-modal';
Modal.setAppElement('#root'); // Important for accessibility
function App() {
return (
Modal content
);
}
export default App;
```
--------------------------------
### Add Custom Data Attributes to React-Modal
Source: https://context7.com/reactjs/react-modal/llms.txt
Leverage the `data` prop in react-modal to add custom data attributes to the modal's content element. These attributes are useful for testing purposes or for creating JavaScript hooks to interact with the modal.
```jsx
import React, { useState } from 'react';
import Modal from 'react-modal';
Modal.setAppElement('#root');
function ModalWithDataAttributes() {
const [isOpen, setIsOpen] = useState(false);
return (
setIsOpen(false)}
data={{
background: 'dark',
testid: 'confirmation-modal',
category: 'user-action'
}}
testId="my-modal"
contentLabel="Modal with Data Attributes"
>
{/* Renders: data-background="dark" data-testid="confirmation-modal" data-category="user-action" */}
Modal Content
);
}
```
--------------------------------
### Configure App Element for Screen Readers (React JSX)
Source: https://github.com/reactjs/react-modal/blob/master/docs/accessibility/index.md
Sets the root element of the React application to manage ARIA hidden attributes for modals. This ensures that only modal content is accessible to screen readers when a modal is open. It accepts a CSS selector string or a DOM element.
```jsx
Modal.setAppElement('#root');
```
```jsx
Modal.setAppElement(document.getElementById('root'));
```
--------------------------------
### Pass ARIA Attributes to Modal (React JSX)
Source: https://github.com/reactjs/react-modal/blob/master/docs/accessibility/index.md
Applies ARIA attributes to the modal for enhanced accessibility. The `contentLabel` prop provides an accessible name, while the `aria` prop allows for custom ARIA attributes like `labelledby` and `describedby` to link the modal to its descriptive content.
```jsx
Alert
Description goes here.
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.