Reactで作られたプロダクト内で、特定のDOMの高さを取得しようとしています。
やりたいこととしては、
jsx
1const hoge = document.querySelector('#hoge'); 2const height = hoge.clientHeight;
のようなシンプルなものです。
ただ、
document.querySelector('#hoge');
をしようとするとdocument is not defined
と怒られるwindow.hogehoge
のようなことをしようとするとwindow is not defined
と怒られるReact.useEffect
内にconsoleを仕込んでも表示されない
と言った形になっています
jsx
1import * as React from 'react'; 2 3function Hoge() { 4 const hoge = document.querySelector('#hoge'); 5 // -> document is not defined 6 7 const hoge2 = window.dataLayer; 8 // -> window is not defined 9 10 React.useEffect(() => { 11 console.log('hogehoge'); 12 // -> 表示されない 13 }); 14 15 return ( 16 <> 17 <div id="hoge">hoge</div> 18 </> 19 ); 20};
if (typeof document !== 'undefined')
やif (typeof window === 'object')
のような分岐をさせてみてもelseの方に入ってしまい引っかからず、documentやwindowが使えません
このような場合、どうしたら良いのでしょうか、、? 🙇♀️

回答2件
あなたの回答
tips
プレビュー