Skip to content

Instantly share code, notes, and snippets.

@Nkzn
Created May 9, 2019 14:52
Show Gist options
  • Save Nkzn/5fd1badf50b3044fe797ea7e703b40be to your computer and use it in GitHub Desktop.
Save Nkzn/5fd1badf50b3044fe797ea7e703b40be to your computer and use it in GitHub Desktop.
コンポーネントがDOMツリーに書き込まれたタイミングで、Reactの外側にコールバックを実行するサンプル
import React from 'react';
export default class ClassComponent extends React.Component {
componentDidMount() {
if (this.ref) {
const event = new CustomEvent('initializedWithClassComponent', { detail: this.ref });
window.dispatchEvent(event);
}
}
render() {
return (
<div className="class-div" ref={ref => this.ref = ref}>
This is class component.
</div>
)
}
}
import React, { useRef, useEffect } from 'react';
export default () => {
const divRef = useRef(null);
useEffect(() => {
if (divRef.current) {
const event = new CustomEvent('initializedWithHooksComponent', { detail: divRef.current });
window.dispatchEvent(event);
}
});
return (
<div className="hooks-div" ref={divRef}>
This is hooks component.
</div>
)
}
<!DOCTYPE html>
<html lang="en">
<head>
<script>
window.addEventListener('initializedWithClassComponent', (e) => {
console.log('initializedWithClassComponent', { detail: e.detail });
// このタイミングでquerySelectorしてもOK
const classDiv = document.querySelector('div.class-div');
console.log('initializedWithClassComponent', { classDiv }); // classDivの中身はe.detailと同じ
}, false);
window.addEventListener('initializedWithHooksComponent', (e) => {
console.log('initialized(or updated)WithHooksComponent', { detail: e.detail });
// このタイミングでquerySelectorしてもOK
const hooksDiv = document.querySelector('div.hooks-div');
console.log('initialized(or updated)WithHooksComponent', { hooksDiv }); // hooksDivの中身はe.detailと同じ
}, false);
</script>
</head>
<body>
<div id="root"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment