admin管理员组文章数量:1321450
I would like to dynamically get the div
element's width. With useRef
, I can get the width of my div
, but when I resize my page, the width value doesn't update automatically. Can you tell me what I need to do to make this happen?
Here's my code I put into Codesandbox.io, and an overview here:
import React from "react";
import "./styles.css";
const App = () => {
const ref = React.useRef(null);
const [width, setWidth] = React.useState(0);
React.useEffect(() => {
setWidth(ref.current.offsetWidth);
}, [width]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<div
style={{
border: "1px solid red"
}}
ref={ref}
>
Width: {width}
</div>
</div>
);
};
export default App;
I would like to dynamically get the div
element's width. With useRef
, I can get the width of my div
, but when I resize my page, the width value doesn't update automatically. Can you tell me what I need to do to make this happen?
Here's my code I put into Codesandbox.io, and an overview here:
import React from "react";
import "./styles.css";
const App = () => {
const ref = React.useRef(null);
const [width, setWidth] = React.useState(0);
React.useEffect(() => {
setWidth(ref.current.offsetWidth);
}, [width]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<div
style={{
border: "1px solid red"
}}
ref={ref}
>
Width: {width}
</div>
</div>
);
};
export default App;
Share
Improve this question
edited Nov 30, 2022 at 15:28
Youssouf Oumar
46.3k16 gold badges101 silver badges104 bronze badges
asked Jun 30, 2022 at 21:21
KatyellenKatyellen
3133 silver badges12 bronze badges
1 Answer
Reset to default 8Change your useEffect
as below, so you add an event listener for when you resize the page. Also, notice I removed the width
state from the dependency array:
import { useEffect, useRef, useState } from "react";
export default function App() {
const ref = useRef(null);
const [width, setWidth] = useState(0);
useEffect(() => {
// when the ponent gets mounted
setWidth(ref.current.offsetWidth);
// to handle page resize
const getwidth = () => {
setWidth(ref.current.offsetWidth);
};
window.addEventListener("resize", getwidth);
// remove the event listener before the ponent gets unmounted
return () => window.removeEventListener("resize", getwidth);
}, []);
return <div ref={ref}>Width: {width}</div>;
}
本文标签: javascriptHow to get HTML element width dynamically even on page resize in ReactStack Overflow
版权声明:本文标题:javascript - How to get HTML element width dynamically even on page resize in React? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742098008a2420669.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论