Created
January 5, 2022 03:23
-
-
Save mironal/1244ba298a38d9b77a6eee1301087d05 to your computer and use it in GitHub Desktop.
Twitter の Widget (widgets.js) を React でかんたんに使うためのやつ(React 以外の依存なし)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from "react" | |
/* | |
index.html などに以下の script をコピペ。 | |
see) https://developer.twitter.com/en/docs/twitter-for-websites/javascript-api/guides/set-up-twitter-for-websites | |
``` | |
<script>window.twttr = (function(d, s, id) { | |
var js, fjs = d.getElementsByTagName(s)[0], | |
t = window.twttr || {}; | |
if (d.getElementById(id)) return t; | |
js = d.createElement(s); | |
js.id = id; | |
js.src = "https://platform.twitter.com/widgets.js"; | |
fjs.parentNode.insertBefore(js, fjs); | |
t._e = []; | |
t.ready = function(f) { | |
t._e.push(f); | |
}; | |
return t; | |
}(document, "script", "twitter-wjs"));</script> | |
``` | |
型情報は `npm i -D @types/twitter-for-web` で入れられます。 | |
see) https://www.npmjs.com/package/@types/twitter-for-web | |
*/ | |
/// TwitterLike はテスト環境などでは読み込めないので undefined も可 | |
const useTwitter = (twitterLike: TwitterLike | undefined) => { | |
const [t, setT] = useState<Twitter | null>(null) | |
useEffect(() => { | |
if (twitterLike) { | |
twitterLike.ready(setT) | |
} | |
}, [twitterLike]) | |
return t | |
} | |
export default useTwitter |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 一例 | |
const HogeComponent = () => { | |
const containerRef = useRef<HTMLDivElement>(null) | |
const twitter = useTwitter(window.twttr) | |
useEffect(() => { | |
if(!twitter || !containerRef.current) { | |
return | |
} | |
twitter.widgets.createFollowButton( | |
"twitter screen name", | |
containerRef.current | |
) | |
return () => { | |
// 追加した widget を削除する | |
document | |
.querySelectorAll(".container > iframe") | |
.forEach((el) => el.remove()) | |
} | |
}, [twitter]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment