ReactJS - Get Height of an elementReactJS get rendered component heightHow do you get the height of a stateless functional component that's a child?Get dimensions and position of an element using pure javascriptAdding ref to Reactstrap Jumbotron causes an errorHow do I detect a click outside an element?How do I check if an element is hidden in jQuery?Event binding on dynamically created elements?How do you get a timestamp in JavaScript?How to get the children of the $(this) selector?How can I get query string values in JavaScript?Get the current URL with JavaScript?How to move an element into another element?How do I remove a particular element from an array in JavaScript?jQuery scroll to element
Is it unprofessional to ask if a job posting on GlassDoor is real?
"to be prejudice towards/against someone" vs "to be prejudiced against/towards someone"
Why do I get two different answers for this counting problem?
Is it legal for company to use my work email to pretend I still work there?
Risk of getting Chronic Wasting Disease (CWD) in the United States?
Have astronauts in space suits ever taken selfies? If so, how?
Example of a continuous function that don't have a continuous extension
"You are your self first supporter", a more proper way to say it
Approximately how much travel time was saved by the opening of the Suez Canal in 1869?
How can I make my BBEG immortal short of making them a Lich or Vampire?
What do you call a Matrix-like slowdown and camera movement effect?
How to say job offer in Mandarin/Cantonese?
How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?
Do I have a twin with permutated remainders?
What do the dots in this tr command do: tr .............A-Z A-ZA-Z <<< "JVPQBOV" (with 13 dots)
Smoothness of finite-dimensional functional calculus
Why are 150k or 200k jobs considered good when there are 300k+ births a month?
Can a Warlock become Neutral Good?
To string or not to string
Why does Kotter return in Welcome Back Kotter?
Why do falling prices hurt debtors?
How to format long polynomial?
Why doesn't Newton's third law mean a person bounces back to where they started when they hit the ground?
What does CI-V stand for?
ReactJS - Get Height of an element
ReactJS get rendered component heightHow do you get the height of a stateless functional component that's a child?Get dimensions and position of an element using pure javascriptAdding ref to Reactstrap Jumbotron causes an errorHow do I detect a click outside an element?How do I check if an element is hidden in jQuery?Event binding on dynamically created elements?How do you get a timestamp in JavaScript?How to get the children of the $(this) selector?How can I get query string values in JavaScript?Get the current URL with JavaScript?How to move an element into another element?How do I remove a particular element from an array in JavaScript?jQuery scroll to element
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
How can I get the Height of an element after React renders that element?
HTML
<div id="container">
<!-- This element's contents will be replaced with your component. -->
<p>
jnknwqkjnkj<br>
jhiwhiw (this is 36px height)
</p>
</div>
ReactJS
var DivSize = React.createClass(
render: function()
let elHeight = document.getElementById('container').clientHeight
return <div className="test">Size: <b>elHeightpx</b> but it should be 18px after the render</div>;
);
ReactDOM.render(
<DivSize />,
document.getElementById('container')
);
RESULT
Size: 36px but it should be 18px after the render
It's calculating the container height before the render (36px). I want to get the height after the render. The right result should be 18px in this case.
https://jsfiddle.net/69z2wepo/29800/
javascript reactjs
add a comment |
How can I get the Height of an element after React renders that element?
HTML
<div id="container">
<!-- This element's contents will be replaced with your component. -->
<p>
jnknwqkjnkj<br>
jhiwhiw (this is 36px height)
</p>
</div>
ReactJS
var DivSize = React.createClass(
render: function()
let elHeight = document.getElementById('container').clientHeight
return <div className="test">Size: <b>elHeightpx</b> but it should be 18px after the render</div>;
);
ReactDOM.render(
<DivSize />,
document.getElementById('container')
);
RESULT
Size: 36px but it should be 18px after the render
It's calculating the container height before the render (36px). I want to get the height after the render. The right result should be 18px in this case.
https://jsfiddle.net/69z2wepo/29800/
javascript reactjs
1
This is not a react question but rather a Javascript and DOM question. You should try to figure out which DOM event you should use to find the final height of your element. In the event handler, you can usesetState
to assign the height value to a state variable.
– mostruash
Feb 2 '16 at 12:45
add a comment |
How can I get the Height of an element after React renders that element?
HTML
<div id="container">
<!-- This element's contents will be replaced with your component. -->
<p>
jnknwqkjnkj<br>
jhiwhiw (this is 36px height)
</p>
</div>
ReactJS
var DivSize = React.createClass(
render: function()
let elHeight = document.getElementById('container').clientHeight
return <div className="test">Size: <b>elHeightpx</b> but it should be 18px after the render</div>;
);
ReactDOM.render(
<DivSize />,
document.getElementById('container')
);
RESULT
Size: 36px but it should be 18px after the render
It's calculating the container height before the render (36px). I want to get the height after the render. The right result should be 18px in this case.
https://jsfiddle.net/69z2wepo/29800/
javascript reactjs
How can I get the Height of an element after React renders that element?
HTML
<div id="container">
<!-- This element's contents will be replaced with your component. -->
<p>
jnknwqkjnkj<br>
jhiwhiw (this is 36px height)
</p>
</div>
ReactJS
var DivSize = React.createClass(
render: function()
let elHeight = document.getElementById('container').clientHeight
return <div className="test">Size: <b>elHeightpx</b> but it should be 18px after the render</div>;
);
ReactDOM.render(
<DivSize />,
document.getElementById('container')
);
RESULT
Size: 36px but it should be 18px after the render
It's calculating the container height before the render (36px). I want to get the height after the render. The right result should be 18px in this case.
https://jsfiddle.net/69z2wepo/29800/
javascript reactjs
javascript reactjs
asked Feb 2 '16 at 12:30
faia20faia20
365138
365138
1
This is not a react question but rather a Javascript and DOM question. You should try to figure out which DOM event you should use to find the final height of your element. In the event handler, you can usesetState
to assign the height value to a state variable.
– mostruash
Feb 2 '16 at 12:45
add a comment |
1
This is not a react question but rather a Javascript and DOM question. You should try to figure out which DOM event you should use to find the final height of your element. In the event handler, you can usesetState
to assign the height value to a state variable.
– mostruash
Feb 2 '16 at 12:45
1
1
This is not a react question but rather a Javascript and DOM question. You should try to figure out which DOM event you should use to find the final height of your element. In the event handler, you can use
setState
to assign the height value to a state variable.– mostruash
Feb 2 '16 at 12:45
This is not a react question but rather a Javascript and DOM question. You should try to figure out which DOM event you should use to find the final height of your element. In the event handler, you can use
setState
to assign the height value to a state variable.– mostruash
Feb 2 '16 at 12:45
add a comment |
4 Answers
4
active
oldest
votes
See this fiddle (actually updated your's)
You need to hook into componentDidMount
which is run after render method. There, you get actual height of element.
5
not correct. see Paul Vincent Beigang's answer below
– ekatz
Nov 14 '17 at 20:47
incorrect fiddle explanation.
– Chandresh
Apr 26 '18 at 6:19
add a comment |
Following is an up to date ES6 example using a ref.
Remember that we have to use a React class component since we need to access the Lifecycle method componentDidMount()
because we can only determine the height of an element after it is rendered in the DOM.
import React, Component from 'react'
import render from 'react-dom'
class DivSize extends Component
constructor(props)
super(props)
this.state =
height: 0
componentDidMount()
const height = this.divElement.clientHeight;
this.setState( height );
render()
return (
<div
className="test"
ref= (divElement) => this.divElement = divElement
>
Size: <b>this.state.heightpx</b> but it should be 18px after the render
</div>
)
render(<DivSize />, document.querySelector('#container'))
You can find the running example here: https://www.webpackbin.com/bins/-KkP1HhC_tW4FeoYSuDe
4
This works but I am getting several eslint errors for Airbnb styleguide:<div ref= divElement => this.divElement = divElement>children</div>
throws "[eslint] Arrow function should not return assignment. (no-return-assign)" andthis.setState( height );
throws "[eslint] Do not use setState in componentDidMount (react/no-did-mount-set-state)". Anyone got a styleguide-compliant solution?
– Timo
Feb 21 '18 at 8:48
5
Wrap the assignment in braces so that it behaves as a function (rather than an expression), like thisref= divElement => this.divElement = divElement
– teletypist
Mar 21 '18 at 22:37
2
This sould be the accepted answer :) Besides, if you want to get the size of the element after the element is updated, you can use the methodcomponentDidUpdate
as well.
– jjimenez
Apr 4 '18 at 11:36
2
is there an alternative to calling this.setState() in componentDidMount with this example?
– danjones_mcr
Aug 28 '18 at 11:10
Good solution. But won't work for responsive designs. If header height was 50px for desktop, and user shrinks the window size, and now height becomes 100px, this solution won't take the updated height. They need to refresh the page to get the changed effects.
– TheCoder
Feb 6 at 19:41
|
show 2 more comments
You would also want to use refs on the element instead of using document.getElementById
, it's just a slightly more robust thing.
add a comment |
For those who are interested in using react hooks
, this might help you get started.
import React, useState, useEffect, useRef from 'react'
export default () =>
const [height, setHeight] = useState(0)
const ref = useRef(null)
useEffect(() =>
setHeight(ref.current.clientHeight)
)
return (
<div ref=ref>
height
</div>
)
Thanks for your answer - it helped me get started. 2 questions though: (1) For these layout-measuring tasks, should we useuseLayoutEffect
instead ofuseEffect
? The docs seem to indicate that we should. See the "tip" section here: reactjs.org/docs/hooks-effect.html#detailed-explanation (2) For these cases where we just need a reference to a child element, should we useuseRef
instead ofcreateRef
? The docs seem to indicate theuseRef
is more appropriate for this use case. See: reactjs.org/docs/hooks-reference.html#useref
– Jason Frank
Mar 4 at 20:55
I just implemented a solution that uses the two items I'm suggesting. They seem to work well, but you may know of some downsides to these choices? Thanks for your help!
– Jason Frank
Mar 4 at 20:55
@JasonFrank Good questions. 1) Both useEffect and useLayoutEffect will be fired after layout and paint. However, useLayoutEffect will fire synchronously before the next paint. I'd say if you really need visual consistency then use useLayoutEffect, otherwise, useEffect should suffice. 2) You're right about that! In a functional component createRef will create a new ref every time the component is being rendered. Using useRef is the better option. I'll update my answer. Thanks!
– Mr. 14
Mar 9 at 2:27
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f35153599%2freactjs-get-height-of-an-element%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
See this fiddle (actually updated your's)
You need to hook into componentDidMount
which is run after render method. There, you get actual height of element.
5
not correct. see Paul Vincent Beigang's answer below
– ekatz
Nov 14 '17 at 20:47
incorrect fiddle explanation.
– Chandresh
Apr 26 '18 at 6:19
add a comment |
See this fiddle (actually updated your's)
You need to hook into componentDidMount
which is run after render method. There, you get actual height of element.
5
not correct. see Paul Vincent Beigang's answer below
– ekatz
Nov 14 '17 at 20:47
incorrect fiddle explanation.
– Chandresh
Apr 26 '18 at 6:19
add a comment |
See this fiddle (actually updated your's)
You need to hook into componentDidMount
which is run after render method. There, you get actual height of element.
See this fiddle (actually updated your's)
You need to hook into componentDidMount
which is run after render method. There, you get actual height of element.
edited Feb 7 '17 at 10:31
Devid Farinelli
5,02152958
5,02152958
answered Feb 2 '16 at 12:46
AndreycoAndreyco
17.1k34459
17.1k34459
5
not correct. see Paul Vincent Beigang's answer below
– ekatz
Nov 14 '17 at 20:47
incorrect fiddle explanation.
– Chandresh
Apr 26 '18 at 6:19
add a comment |
5
not correct. see Paul Vincent Beigang's answer below
– ekatz
Nov 14 '17 at 20:47
incorrect fiddle explanation.
– Chandresh
Apr 26 '18 at 6:19
5
5
not correct. see Paul Vincent Beigang's answer below
– ekatz
Nov 14 '17 at 20:47
not correct. see Paul Vincent Beigang's answer below
– ekatz
Nov 14 '17 at 20:47
incorrect fiddle explanation.
– Chandresh
Apr 26 '18 at 6:19
incorrect fiddle explanation.
– Chandresh
Apr 26 '18 at 6:19
add a comment |
Following is an up to date ES6 example using a ref.
Remember that we have to use a React class component since we need to access the Lifecycle method componentDidMount()
because we can only determine the height of an element after it is rendered in the DOM.
import React, Component from 'react'
import render from 'react-dom'
class DivSize extends Component
constructor(props)
super(props)
this.state =
height: 0
componentDidMount()
const height = this.divElement.clientHeight;
this.setState( height );
render()
return (
<div
className="test"
ref= (divElement) => this.divElement = divElement
>
Size: <b>this.state.heightpx</b> but it should be 18px after the render
</div>
)
render(<DivSize />, document.querySelector('#container'))
You can find the running example here: https://www.webpackbin.com/bins/-KkP1HhC_tW4FeoYSuDe
4
This works but I am getting several eslint errors for Airbnb styleguide:<div ref= divElement => this.divElement = divElement>children</div>
throws "[eslint] Arrow function should not return assignment. (no-return-assign)" andthis.setState( height );
throws "[eslint] Do not use setState in componentDidMount (react/no-did-mount-set-state)". Anyone got a styleguide-compliant solution?
– Timo
Feb 21 '18 at 8:48
5
Wrap the assignment in braces so that it behaves as a function (rather than an expression), like thisref= divElement => this.divElement = divElement
– teletypist
Mar 21 '18 at 22:37
2
This sould be the accepted answer :) Besides, if you want to get the size of the element after the element is updated, you can use the methodcomponentDidUpdate
as well.
– jjimenez
Apr 4 '18 at 11:36
2
is there an alternative to calling this.setState() in componentDidMount with this example?
– danjones_mcr
Aug 28 '18 at 11:10
Good solution. But won't work for responsive designs. If header height was 50px for desktop, and user shrinks the window size, and now height becomes 100px, this solution won't take the updated height. They need to refresh the page to get the changed effects.
– TheCoder
Feb 6 at 19:41
|
show 2 more comments
Following is an up to date ES6 example using a ref.
Remember that we have to use a React class component since we need to access the Lifecycle method componentDidMount()
because we can only determine the height of an element after it is rendered in the DOM.
import React, Component from 'react'
import render from 'react-dom'
class DivSize extends Component
constructor(props)
super(props)
this.state =
height: 0
componentDidMount()
const height = this.divElement.clientHeight;
this.setState( height );
render()
return (
<div
className="test"
ref= (divElement) => this.divElement = divElement
>
Size: <b>this.state.heightpx</b> but it should be 18px after the render
</div>
)
render(<DivSize />, document.querySelector('#container'))
You can find the running example here: https://www.webpackbin.com/bins/-KkP1HhC_tW4FeoYSuDe
4
This works but I am getting several eslint errors for Airbnb styleguide:<div ref= divElement => this.divElement = divElement>children</div>
throws "[eslint] Arrow function should not return assignment. (no-return-assign)" andthis.setState( height );
throws "[eslint] Do not use setState in componentDidMount (react/no-did-mount-set-state)". Anyone got a styleguide-compliant solution?
– Timo
Feb 21 '18 at 8:48
5
Wrap the assignment in braces so that it behaves as a function (rather than an expression), like thisref= divElement => this.divElement = divElement
– teletypist
Mar 21 '18 at 22:37
2
This sould be the accepted answer :) Besides, if you want to get the size of the element after the element is updated, you can use the methodcomponentDidUpdate
as well.
– jjimenez
Apr 4 '18 at 11:36
2
is there an alternative to calling this.setState() in componentDidMount with this example?
– danjones_mcr
Aug 28 '18 at 11:10
Good solution. But won't work for responsive designs. If header height was 50px for desktop, and user shrinks the window size, and now height becomes 100px, this solution won't take the updated height. They need to refresh the page to get the changed effects.
– TheCoder
Feb 6 at 19:41
|
show 2 more comments
Following is an up to date ES6 example using a ref.
Remember that we have to use a React class component since we need to access the Lifecycle method componentDidMount()
because we can only determine the height of an element after it is rendered in the DOM.
import React, Component from 'react'
import render from 'react-dom'
class DivSize extends Component
constructor(props)
super(props)
this.state =
height: 0
componentDidMount()
const height = this.divElement.clientHeight;
this.setState( height );
render()
return (
<div
className="test"
ref= (divElement) => this.divElement = divElement
>
Size: <b>this.state.heightpx</b> but it should be 18px after the render
</div>
)
render(<DivSize />, document.querySelector('#container'))
You can find the running example here: https://www.webpackbin.com/bins/-KkP1HhC_tW4FeoYSuDe
Following is an up to date ES6 example using a ref.
Remember that we have to use a React class component since we need to access the Lifecycle method componentDidMount()
because we can only determine the height of an element after it is rendered in the DOM.
import React, Component from 'react'
import render from 'react-dom'
class DivSize extends Component
constructor(props)
super(props)
this.state =
height: 0
componentDidMount()
const height = this.divElement.clientHeight;
this.setState( height );
render()
return (
<div
className="test"
ref= (divElement) => this.divElement = divElement
>
Size: <b>this.state.heightpx</b> but it should be 18px after the render
</div>
)
render(<DivSize />, document.querySelector('#container'))
You can find the running example here: https://www.webpackbin.com/bins/-KkP1HhC_tW4FeoYSuDe
answered May 18 '17 at 5:37
Paul Vincent BeigangPaul Vincent Beigang
1,22421018
1,22421018
4
This works but I am getting several eslint errors for Airbnb styleguide:<div ref= divElement => this.divElement = divElement>children</div>
throws "[eslint] Arrow function should not return assignment. (no-return-assign)" andthis.setState( height );
throws "[eslint] Do not use setState in componentDidMount (react/no-did-mount-set-state)". Anyone got a styleguide-compliant solution?
– Timo
Feb 21 '18 at 8:48
5
Wrap the assignment in braces so that it behaves as a function (rather than an expression), like thisref= divElement => this.divElement = divElement
– teletypist
Mar 21 '18 at 22:37
2
This sould be the accepted answer :) Besides, if you want to get the size of the element after the element is updated, you can use the methodcomponentDidUpdate
as well.
– jjimenez
Apr 4 '18 at 11:36
2
is there an alternative to calling this.setState() in componentDidMount with this example?
– danjones_mcr
Aug 28 '18 at 11:10
Good solution. But won't work for responsive designs. If header height was 50px for desktop, and user shrinks the window size, and now height becomes 100px, this solution won't take the updated height. They need to refresh the page to get the changed effects.
– TheCoder
Feb 6 at 19:41
|
show 2 more comments
4
This works but I am getting several eslint errors for Airbnb styleguide:<div ref= divElement => this.divElement = divElement>children</div>
throws "[eslint] Arrow function should not return assignment. (no-return-assign)" andthis.setState( height );
throws "[eslint] Do not use setState in componentDidMount (react/no-did-mount-set-state)". Anyone got a styleguide-compliant solution?
– Timo
Feb 21 '18 at 8:48
5
Wrap the assignment in braces so that it behaves as a function (rather than an expression), like thisref= divElement => this.divElement = divElement
– teletypist
Mar 21 '18 at 22:37
2
This sould be the accepted answer :) Besides, if you want to get the size of the element after the element is updated, you can use the methodcomponentDidUpdate
as well.
– jjimenez
Apr 4 '18 at 11:36
2
is there an alternative to calling this.setState() in componentDidMount with this example?
– danjones_mcr
Aug 28 '18 at 11:10
Good solution. But won't work for responsive designs. If header height was 50px for desktop, and user shrinks the window size, and now height becomes 100px, this solution won't take the updated height. They need to refresh the page to get the changed effects.
– TheCoder
Feb 6 at 19:41
4
4
This works but I am getting several eslint errors for Airbnb styleguide:
<div ref= divElement => this.divElement = divElement>children</div>
throws "[eslint] Arrow function should not return assignment. (no-return-assign)" and this.setState( height );
throws "[eslint] Do not use setState in componentDidMount (react/no-did-mount-set-state)". Anyone got a styleguide-compliant solution?– Timo
Feb 21 '18 at 8:48
This works but I am getting several eslint errors for Airbnb styleguide:
<div ref= divElement => this.divElement = divElement>children</div>
throws "[eslint] Arrow function should not return assignment. (no-return-assign)" and this.setState( height );
throws "[eslint] Do not use setState in componentDidMount (react/no-did-mount-set-state)". Anyone got a styleguide-compliant solution?– Timo
Feb 21 '18 at 8:48
5
5
Wrap the assignment in braces so that it behaves as a function (rather than an expression), like this
ref= divElement => this.divElement = divElement
– teletypist
Mar 21 '18 at 22:37
Wrap the assignment in braces so that it behaves as a function (rather than an expression), like this
ref= divElement => this.divElement = divElement
– teletypist
Mar 21 '18 at 22:37
2
2
This sould be the accepted answer :) Besides, if you want to get the size of the element after the element is updated, you can use the method
componentDidUpdate
as well.– jjimenez
Apr 4 '18 at 11:36
This sould be the accepted answer :) Besides, if you want to get the size of the element after the element is updated, you can use the method
componentDidUpdate
as well.– jjimenez
Apr 4 '18 at 11:36
2
2
is there an alternative to calling this.setState() in componentDidMount with this example?
– danjones_mcr
Aug 28 '18 at 11:10
is there an alternative to calling this.setState() in componentDidMount with this example?
– danjones_mcr
Aug 28 '18 at 11:10
Good solution. But won't work for responsive designs. If header height was 50px for desktop, and user shrinks the window size, and now height becomes 100px, this solution won't take the updated height. They need to refresh the page to get the changed effects.
– TheCoder
Feb 6 at 19:41
Good solution. But won't work for responsive designs. If header height was 50px for desktop, and user shrinks the window size, and now height becomes 100px, this solution won't take the updated height. They need to refresh the page to get the changed effects.
– TheCoder
Feb 6 at 19:41
|
show 2 more comments
You would also want to use refs on the element instead of using document.getElementById
, it's just a slightly more robust thing.
add a comment |
You would also want to use refs on the element instead of using document.getElementById
, it's just a slightly more robust thing.
add a comment |
You would also want to use refs on the element instead of using document.getElementById
, it's just a slightly more robust thing.
You would also want to use refs on the element instead of using document.getElementById
, it's just a slightly more robust thing.
edited Feb 7 '17 at 10:32
Devid Farinelli
5,02152958
5,02152958
answered Jan 27 '17 at 0:42
yoyodunnoyoyodunno
336316
336316
add a comment |
add a comment |
For those who are interested in using react hooks
, this might help you get started.
import React, useState, useEffect, useRef from 'react'
export default () =>
const [height, setHeight] = useState(0)
const ref = useRef(null)
useEffect(() =>
setHeight(ref.current.clientHeight)
)
return (
<div ref=ref>
height
</div>
)
Thanks for your answer - it helped me get started. 2 questions though: (1) For these layout-measuring tasks, should we useuseLayoutEffect
instead ofuseEffect
? The docs seem to indicate that we should. See the "tip" section here: reactjs.org/docs/hooks-effect.html#detailed-explanation (2) For these cases where we just need a reference to a child element, should we useuseRef
instead ofcreateRef
? The docs seem to indicate theuseRef
is more appropriate for this use case. See: reactjs.org/docs/hooks-reference.html#useref
– Jason Frank
Mar 4 at 20:55
I just implemented a solution that uses the two items I'm suggesting. They seem to work well, but you may know of some downsides to these choices? Thanks for your help!
– Jason Frank
Mar 4 at 20:55
@JasonFrank Good questions. 1) Both useEffect and useLayoutEffect will be fired after layout and paint. However, useLayoutEffect will fire synchronously before the next paint. I'd say if you really need visual consistency then use useLayoutEffect, otherwise, useEffect should suffice. 2) You're right about that! In a functional component createRef will create a new ref every time the component is being rendered. Using useRef is the better option. I'll update my answer. Thanks!
– Mr. 14
Mar 9 at 2:27
add a comment |
For those who are interested in using react hooks
, this might help you get started.
import React, useState, useEffect, useRef from 'react'
export default () =>
const [height, setHeight] = useState(0)
const ref = useRef(null)
useEffect(() =>
setHeight(ref.current.clientHeight)
)
return (
<div ref=ref>
height
</div>
)
Thanks for your answer - it helped me get started. 2 questions though: (1) For these layout-measuring tasks, should we useuseLayoutEffect
instead ofuseEffect
? The docs seem to indicate that we should. See the "tip" section here: reactjs.org/docs/hooks-effect.html#detailed-explanation (2) For these cases where we just need a reference to a child element, should we useuseRef
instead ofcreateRef
? The docs seem to indicate theuseRef
is more appropriate for this use case. See: reactjs.org/docs/hooks-reference.html#useref
– Jason Frank
Mar 4 at 20:55
I just implemented a solution that uses the two items I'm suggesting. They seem to work well, but you may know of some downsides to these choices? Thanks for your help!
– Jason Frank
Mar 4 at 20:55
@JasonFrank Good questions. 1) Both useEffect and useLayoutEffect will be fired after layout and paint. However, useLayoutEffect will fire synchronously before the next paint. I'd say if you really need visual consistency then use useLayoutEffect, otherwise, useEffect should suffice. 2) You're right about that! In a functional component createRef will create a new ref every time the component is being rendered. Using useRef is the better option. I'll update my answer. Thanks!
– Mr. 14
Mar 9 at 2:27
add a comment |
For those who are interested in using react hooks
, this might help you get started.
import React, useState, useEffect, useRef from 'react'
export default () =>
const [height, setHeight] = useState(0)
const ref = useRef(null)
useEffect(() =>
setHeight(ref.current.clientHeight)
)
return (
<div ref=ref>
height
</div>
)
For those who are interested in using react hooks
, this might help you get started.
import React, useState, useEffect, useRef from 'react'
export default () =>
const [height, setHeight] = useState(0)
const ref = useRef(null)
useEffect(() =>
setHeight(ref.current.clientHeight)
)
return (
<div ref=ref>
height
</div>
)
edited Mar 9 at 2:28
answered Feb 23 at 12:57
Mr. 14Mr. 14
4,75122644
4,75122644
Thanks for your answer - it helped me get started. 2 questions though: (1) For these layout-measuring tasks, should we useuseLayoutEffect
instead ofuseEffect
? The docs seem to indicate that we should. See the "tip" section here: reactjs.org/docs/hooks-effect.html#detailed-explanation (2) For these cases where we just need a reference to a child element, should we useuseRef
instead ofcreateRef
? The docs seem to indicate theuseRef
is more appropriate for this use case. See: reactjs.org/docs/hooks-reference.html#useref
– Jason Frank
Mar 4 at 20:55
I just implemented a solution that uses the two items I'm suggesting. They seem to work well, but you may know of some downsides to these choices? Thanks for your help!
– Jason Frank
Mar 4 at 20:55
@JasonFrank Good questions. 1) Both useEffect and useLayoutEffect will be fired after layout and paint. However, useLayoutEffect will fire synchronously before the next paint. I'd say if you really need visual consistency then use useLayoutEffect, otherwise, useEffect should suffice. 2) You're right about that! In a functional component createRef will create a new ref every time the component is being rendered. Using useRef is the better option. I'll update my answer. Thanks!
– Mr. 14
Mar 9 at 2:27
add a comment |
Thanks for your answer - it helped me get started. 2 questions though: (1) For these layout-measuring tasks, should we useuseLayoutEffect
instead ofuseEffect
? The docs seem to indicate that we should. See the "tip" section here: reactjs.org/docs/hooks-effect.html#detailed-explanation (2) For these cases where we just need a reference to a child element, should we useuseRef
instead ofcreateRef
? The docs seem to indicate theuseRef
is more appropriate for this use case. See: reactjs.org/docs/hooks-reference.html#useref
– Jason Frank
Mar 4 at 20:55
I just implemented a solution that uses the two items I'm suggesting. They seem to work well, but you may know of some downsides to these choices? Thanks for your help!
– Jason Frank
Mar 4 at 20:55
@JasonFrank Good questions. 1) Both useEffect and useLayoutEffect will be fired after layout and paint. However, useLayoutEffect will fire synchronously before the next paint. I'd say if you really need visual consistency then use useLayoutEffect, otherwise, useEffect should suffice. 2) You're right about that! In a functional component createRef will create a new ref every time the component is being rendered. Using useRef is the better option. I'll update my answer. Thanks!
– Mr. 14
Mar 9 at 2:27
Thanks for your answer - it helped me get started. 2 questions though: (1) For these layout-measuring tasks, should we use
useLayoutEffect
instead of useEffect
? The docs seem to indicate that we should. See the "tip" section here: reactjs.org/docs/hooks-effect.html#detailed-explanation (2) For these cases where we just need a reference to a child element, should we use useRef
instead of createRef
? The docs seem to indicate the useRef
is more appropriate for this use case. See: reactjs.org/docs/hooks-reference.html#useref– Jason Frank
Mar 4 at 20:55
Thanks for your answer - it helped me get started. 2 questions though: (1) For these layout-measuring tasks, should we use
useLayoutEffect
instead of useEffect
? The docs seem to indicate that we should. See the "tip" section here: reactjs.org/docs/hooks-effect.html#detailed-explanation (2) For these cases where we just need a reference to a child element, should we use useRef
instead of createRef
? The docs seem to indicate the useRef
is more appropriate for this use case. See: reactjs.org/docs/hooks-reference.html#useref– Jason Frank
Mar 4 at 20:55
I just implemented a solution that uses the two items I'm suggesting. They seem to work well, but you may know of some downsides to these choices? Thanks for your help!
– Jason Frank
Mar 4 at 20:55
I just implemented a solution that uses the two items I'm suggesting. They seem to work well, but you may know of some downsides to these choices? Thanks for your help!
– Jason Frank
Mar 4 at 20:55
@JasonFrank Good questions. 1) Both useEffect and useLayoutEffect will be fired after layout and paint. However, useLayoutEffect will fire synchronously before the next paint. I'd say if you really need visual consistency then use useLayoutEffect, otherwise, useEffect should suffice. 2) You're right about that! In a functional component createRef will create a new ref every time the component is being rendered. Using useRef is the better option. I'll update my answer. Thanks!
– Mr. 14
Mar 9 at 2:27
@JasonFrank Good questions. 1) Both useEffect and useLayoutEffect will be fired after layout and paint. However, useLayoutEffect will fire synchronously before the next paint. I'd say if you really need visual consistency then use useLayoutEffect, otherwise, useEffect should suffice. 2) You're right about that! In a functional component createRef will create a new ref every time the component is being rendered. Using useRef is the better option. I'll update my answer. Thanks!
– Mr. 14
Mar 9 at 2:27
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f35153599%2freactjs-get-height-of-an-element%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
This is not a react question but rather a Javascript and DOM question. You should try to figure out which DOM event you should use to find the final height of your element. In the event handler, you can use
setState
to assign the height value to a state variable.– mostruash
Feb 2 '16 at 12:45