Skip to content

Commit cd60b15

Browse files
pedroapfilhokentcdodds
authored andcommitted
Fixing modal example to use hooks (testing-library#315)
* fixing modal example to use hooks * removing css and adding correct imports * keep react-dom for createPortal Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
1 parent 717da63 commit cd60b15

File tree

1 file changed

+20
-48
lines changed

1 file changed

+20
-48
lines changed

docs/example-react-modal.md

Lines changed: 20 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -4,61 +4,33 @@ title: Modals
44
---
55

66
```jsx
7-
import React from 'react'
7+
import React, { useEffect } from 'react'
88
import ReactDOM from 'react-dom'
99
import { render, fireEvent } from '@testing-library/react'
1010

1111
const modalRoot = document.createElement('div')
1212
modalRoot.setAttribute('id', 'modal-root')
1313
document.body.appendChild(modalRoot)
1414

15-
class Modal extends React.Component {
16-
el = document.createElement('div')
17-
componentDidMount() {
18-
modalRoot.appendChild(this.el)
19-
}
20-
componentWillUnmount() {
21-
modalRoot.removeChild(this.el)
22-
}
23-
render() {
24-
return ReactDOM.createPortal(
25-
<div
26-
style={{
27-
position: 'absolute',
28-
top: '0',
29-
bottom: '0',
30-
left: '0',
31-
right: '0',
32-
display: 'grid',
33-
justifyContent: 'center',
34-
alignItems: 'center',
35-
backgroundColor: 'rgba(0,0,0,0.3)',
36-
}}
37-
onClick={this.props.onClose}
38-
>
39-
<div
40-
style={{
41-
padding: 20,
42-
background: '#fff',
43-
borderRadius: '2px',
44-
display: 'inline-block',
45-
minHeight: '300px',
46-
margin: '1rem',
47-
position: 'relative',
48-
minWidth: '300px',
49-
boxShadow: '0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23)',
50-
justifySelf: 'center',
51-
}}
52-
onClick={e => e.stopPropagation()}
53-
>
54-
{this.props.children}
55-
<hr />
56-
<button onClick={this.props.onClose}>Close</button>
57-
</div>
58-
</div>,
59-
this.el
60-
)
61-
}
15+
const App = ({ onClose, children }) => {
16+
const el = document.createElement('div')
17+
18+
useEffect(() => {
19+
modalRoot.appendChild(el)
20+
21+
return () => modalRoot.removeChild(el)
22+
})
23+
24+
return ReactDOM.createPortal(
25+
<div onClick={onClose}>
26+
<div onClick={e => e.stopPropagation()}>
27+
{children}
28+
<hr />
29+
<button onClick={onClose}>Close</button>
30+
</div>
31+
</div>,
32+
el
33+
)
6234
}
6335

6436
test('modal shows the children and a close button', () => {

0 commit comments

Comments
 (0)