๋ฒ๊ทธ ์ค๋ช
ReactDOM.createPortal์์ ๋ง๋ Modal ๊ตฌ์ฑ ์์์ ์ด์ผ๊ธฐ๋ฅผ ์ถ๊ฐํ๊ณ ์ถ์ต๋๋ค.
๋ชจ๋ฌ ์ปจํ
์ด๋๋ ๋ด๊ฐ index.html์ ์ถ๊ฐ ํ <div id="modal-root"></div>
์
๋๋ค.
ํ์ง๋ง ์ด๋ ๊ฒ ์ด์ผ๊ธฐ๋ฅผ ์ธ ๋ :
storiesOf('atoms/modal', module)
.addDecorator(withKnobs)
.add('Modal', () => (
<Modal
isOpen={true}
onRequestClose={action('onRequestClose')}
>
<div>modal</div>
</Modal>
))
ใ๋์ ์ปจํ ์ด๋๊ฐ DOM ์์๊ฐ ์๋๋๋คใ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.
Storybook UI์ ๋ชจ๋ฌ ๋ฃจํธ div๊ฐ ์๊ธฐ ๋๋ฌธ์ด๋ผ๊ณ ์๊ฐํฉ๋๊น?
์ด๋ป๊ฒ ๊ณ ์น ์ ์์ต๋๊น?
์ฌํํ๋ ค๋ฉด
์ ์ฐธ์กฐ
์คํฌ๋ฆฐ ์ท
์ฝ๋ ์กฐ๊ฐ
์ด๊ฒ์ ๋ด ๋ชจ๋ฌ ์ฝ๋์
๋๋ค.
const modalRoot = document.getElementById('modal-root')
class Modal extends React.Component {
constructor(props) {
super(props)
this.el = document.createElement('div')
}
componentDidMount() {
modalRoot.appendChild(this.el)
}
componentWillUnmount() {
modalRoot.removeChild(this.el)
}
handleClickBackDrop = event => {
this.props.onRequestClose(event)
}
render() {
const { isOpen, children } = this.props
if (!isOpen) {
return null
}
const modalUI = (
<BackDropWrapper
onClick={this.handleClickBackDrop}
>
<ModalWrapper>
{children}
</ModalWrapper>
</BackDropWrapper>
)
return ReactDOM.createPortal(modalUI, modalRoot)
}
}
์ฒด๊ณ:
const modalRoot = document.getElementById('modal-root')
๋ ์ ์ ์ผ๋ก ํธ์ถ๋๋ฏ๋ก Modal
๊ตฌ์ฑ ์์๋ฅผ ๊ฐ์ ธ ์ค๊ธฐ ์ ์ <div id="modal-root">
๋ฅผ ์์ฑํด์ผํฉ๋๋ค. ์คํ ๋ฆฌ๋ฅผ๋ก๋ํ๊ธฐ ์ ์ config.js
์์์ด div๋ฅผ ๋ง๋๋ ๊ฒ์ด ์ข์ต๋๋ค.
์ด ๊ฐ์:
// config.js
const modalRoot = document.createElement('div');
modalRoot.setAttribute('id', 'modal-root');
document.body.append(modalRoot);
@ igor-dv ๊ทํ์ ์ ์์ด ํจ๊ณผ๊ฐ ์์์ ๊ฐ์ฌ๋๋ฆฝ๋๋ค.
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
const modalRoot = document.getElementById('modal-root')
๋ ์ ์ ์ผ๋ก ํธ์ถ๋๋ฏ๋กModal
๊ตฌ์ฑ ์์๋ฅผ ๊ฐ์ ธ ์ค๊ธฐ ์ ์<div id="modal-root">
๋ฅผ ์์ฑํด์ผํฉ๋๋ค. ์คํ ๋ฆฌ๋ฅผ๋ก๋ํ๊ธฐ ์ ์config.js
์์์ด div๋ฅผ ๋ง๋๋ ๊ฒ์ด ์ข์ต๋๋ค.์ด ๊ฐ์: