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;








66















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/










share|improve this question

















  • 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

















66















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/










share|improve this question

















  • 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













66












66








66


12






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/










share|improve this question














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






share|improve this question













share|improve this question











share|improve this question




share|improve this question










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 use setState to assign the height value to a state variable.

    – mostruash
    Feb 2 '16 at 12:45












  • 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







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












4 Answers
4






active

oldest

votes


















22














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.






share|improve this answer




















  • 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


















100














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






share|improve this answer


















  • 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







  • 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







  • 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






  • 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


















8














You would also want to use refs on the element instead of using document.getElementById, it's just a slightly more robust thing.






share|improve this answer
































    8














    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>
    )






    share|improve this answer

























    • 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











    • @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











    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
    );



    );













    draft saved

    draft discarded


















    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









    22














    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.






    share|improve this answer




















    • 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















    22














    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.






    share|improve this answer




















    • 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













    22












    22








    22







    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.






    share|improve this answer















    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.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    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












    • 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













    100














    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






    share|improve this answer


















    • 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







    • 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







    • 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






    • 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















    100














    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






    share|improve this answer


















    • 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







    • 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







    • 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






    • 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













    100












    100








    100







    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






    share|improve this answer













    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







    share|improve this answer












    share|improve this answer



    share|improve this answer










    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)" 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





      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





      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





      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





      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





      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





      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





      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











    8














    You would also want to use refs on the element instead of using document.getElementById, it's just a slightly more robust thing.






    share|improve this answer





























      8














      You would also want to use refs on the element instead of using document.getElementById, it's just a slightly more robust thing.






      share|improve this answer



























        8












        8








        8







        You would also want to use refs on the element instead of using document.getElementById, it's just a slightly more robust thing.






        share|improve this answer















        You would also want to use refs on the element instead of using document.getElementById, it's just a slightly more robust thing.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Feb 7 '17 at 10:32









        Devid Farinelli

        5,02152958




        5,02152958










        answered Jan 27 '17 at 0:42









        yoyodunnoyoyodunno

        336316




        336316





















            8














            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>
            )






            share|improve this answer

























            • 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











            • @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















            8














            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>
            )






            share|improve this answer

























            • 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











            • @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













            8












            8








            8







            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>
            )






            share|improve this answer















            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>
            )







            share|improve this answer














            share|improve this answer



            share|improve this answer








            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 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











            • @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











            • 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

















            draft saved

            draft discarded
















































            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.




            draft saved


            draft discarded














            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





















































            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







            Popular posts from this blog

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived