react - get width/height of image to process











up vote
1
down vote

favorite












I was wondering how to get the height and width of an image if I'm rendering it react style so I can process it to flip it to portrait mode if the width is larger than the height.



Example: https://codesandbox.io/s/k9kwv0kp93



Example code:



index.js



import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';

const styles = {
fontFamily: 'sans-serif',
textAlign: 'center',
};

const App = () => (
<div style={styles}>
<Hello name="CodeSandbox" />
<h2>Start editing to see some magic happen {'u2728'}</h2>
</div>
);

render(<App />, document.getElementById('root'));


Hello.js



import React, {Component} from 'react';

export default class Hello extends Component
{
constructor()
{
super();
this.state = {img: null}

this.get_image = this.get_image.bind(this);
}

get_image()
{
let img = <img src="http://via.placeholder.com/350x150" alt="" />;
//manipulate here maybe
this.setState({
img
})
}

render()
{
return (
<div>
<button onClick={this.get_image}>Click me</button>
test
{this.state.img}
</div>
)
}
}









share|improve this question


























    up vote
    1
    down vote

    favorite












    I was wondering how to get the height and width of an image if I'm rendering it react style so I can process it to flip it to portrait mode if the width is larger than the height.



    Example: https://codesandbox.io/s/k9kwv0kp93



    Example code:



    index.js



    import React from 'react';
    import { render } from 'react-dom';
    import Hello from './Hello';

    const styles = {
    fontFamily: 'sans-serif',
    textAlign: 'center',
    };

    const App = () => (
    <div style={styles}>
    <Hello name="CodeSandbox" />
    <h2>Start editing to see some magic happen {'u2728'}</h2>
    </div>
    );

    render(<App />, document.getElementById('root'));


    Hello.js



    import React, {Component} from 'react';

    export default class Hello extends Component
    {
    constructor()
    {
    super();
    this.state = {img: null}

    this.get_image = this.get_image.bind(this);
    }

    get_image()
    {
    let img = <img src="http://via.placeholder.com/350x150" alt="" />;
    //manipulate here maybe
    this.setState({
    img
    })
    }

    render()
    {
    return (
    <div>
    <button onClick={this.get_image}>Click me</button>
    test
    {this.state.img}
    </div>
    )
    }
    }









    share|improve this question
























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I was wondering how to get the height and width of an image if I'm rendering it react style so I can process it to flip it to portrait mode if the width is larger than the height.



      Example: https://codesandbox.io/s/k9kwv0kp93



      Example code:



      index.js



      import React from 'react';
      import { render } from 'react-dom';
      import Hello from './Hello';

      const styles = {
      fontFamily: 'sans-serif',
      textAlign: 'center',
      };

      const App = () => (
      <div style={styles}>
      <Hello name="CodeSandbox" />
      <h2>Start editing to see some magic happen {'u2728'}</h2>
      </div>
      );

      render(<App />, document.getElementById('root'));


      Hello.js



      import React, {Component} from 'react';

      export default class Hello extends Component
      {
      constructor()
      {
      super();
      this.state = {img: null}

      this.get_image = this.get_image.bind(this);
      }

      get_image()
      {
      let img = <img src="http://via.placeholder.com/350x150" alt="" />;
      //manipulate here maybe
      this.setState({
      img
      })
      }

      render()
      {
      return (
      <div>
      <button onClick={this.get_image}>Click me</button>
      test
      {this.state.img}
      </div>
      )
      }
      }









      share|improve this question













      I was wondering how to get the height and width of an image if I'm rendering it react style so I can process it to flip it to portrait mode if the width is larger than the height.



      Example: https://codesandbox.io/s/k9kwv0kp93



      Example code:



      index.js



      import React from 'react';
      import { render } from 'react-dom';
      import Hello from './Hello';

      const styles = {
      fontFamily: 'sans-serif',
      textAlign: 'center',
      };

      const App = () => (
      <div style={styles}>
      <Hello name="CodeSandbox" />
      <h2>Start editing to see some magic happen {'u2728'}</h2>
      </div>
      );

      render(<App />, document.getElementById('root'));


      Hello.js



      import React, {Component} from 'react';

      export default class Hello extends Component
      {
      constructor()
      {
      super();
      this.state = {img: null}

      this.get_image = this.get_image.bind(this);
      }

      get_image()
      {
      let img = <img src="http://via.placeholder.com/350x150" alt="" />;
      //manipulate here maybe
      this.setState({
      img
      })
      }

      render()
      {
      return (
      <div>
      <button onClick={this.get_image}>Click me</button>
      test
      {this.state.img}
      </div>
      )
      }
      }






      javascript css reactjs






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Sep 4 '17 at 4:03









      A. Lau

      3,18951850




      3,18951850
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          2
          down vote



          accepted











          React supports a special attribute that you can attach to any component. The ref attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted.



          When the ref attribute is used on an HTML element, the ref callback receives the underlying DOM element as its argument




          Taken from: https://facebook.github.io/react/docs/refs-and-the-dom.html






          class MyComponent extends React.Component {
          constructor(props) {
          super(props);
          }

          handleSize(image) {
          console.log(image.offsetWidth, image.offsetHeight)
          }

          render() {
          return React.createElement("img", {
          src: "http://cdn.collider.com/wp-content/uploads/2016/07/narcos-season-2-image-5.jpg",
          ref: image => {
          this.handleSize(image);
          }
          });
          }
          }

          ReactDOM.render(React.createElement(MyComponent, null), document.getElementById('root'))

          img {
          width: 200px;
          height: 133px;
          }

          <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-with-addons.min.js">
          </script>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

          <div id="root"></div>








          share|improve this answer























          • around the right idea, but it's returning 0 for both height and width. Tried to add an onLoad to it too but it didn't change the results :S
            – A. Lau
            Sep 4 '17 at 5:23










          • Please share your attempts
            – felixmosh
            Sep 4 '17 at 5:55










          • I might rename the question since it's more about onload.
            – A. Lau
            Sep 4 '17 at 8:41










          • I've updated the answer to real implementation. React will execute ref callback immediately after the component is mounted, so no need for onLoad on the image itself
            – felixmosh
            Sep 4 '17 at 9:01












          • why is the offsetHeight 0 though?
            – A. Lau
            Sep 4 '17 at 10:48


















          up vote
          0
          down vote













          i encountered the same issue, i was able to get the img height/width using refs and onLoad.



          render() {
          return (
          <img
          src='https://via.placeholder.com/150'
          ref={el = this.imgEl = el}
          onLoad={() => console.log(this.imgEl.naturalHeight)} // print 150
          />
          )
          }




          Also you should use img.naturalHeight






          share|improve this answer























            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',
            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%2f46030129%2freact-get-width-height-of-image-to-process%23new-answer', 'question_page');
            }
            );

            Post as a guest
































            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            2
            down vote



            accepted











            React supports a special attribute that you can attach to any component. The ref attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted.



            When the ref attribute is used on an HTML element, the ref callback receives the underlying DOM element as its argument




            Taken from: https://facebook.github.io/react/docs/refs-and-the-dom.html






            class MyComponent extends React.Component {
            constructor(props) {
            super(props);
            }

            handleSize(image) {
            console.log(image.offsetWidth, image.offsetHeight)
            }

            render() {
            return React.createElement("img", {
            src: "http://cdn.collider.com/wp-content/uploads/2016/07/narcos-season-2-image-5.jpg",
            ref: image => {
            this.handleSize(image);
            }
            });
            }
            }

            ReactDOM.render(React.createElement(MyComponent, null), document.getElementById('root'))

            img {
            width: 200px;
            height: 133px;
            }

            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-with-addons.min.js">
            </script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

            <div id="root"></div>








            share|improve this answer























            • around the right idea, but it's returning 0 for both height and width. Tried to add an onLoad to it too but it didn't change the results :S
              – A. Lau
              Sep 4 '17 at 5:23










            • Please share your attempts
              – felixmosh
              Sep 4 '17 at 5:55










            • I might rename the question since it's more about onload.
              – A. Lau
              Sep 4 '17 at 8:41










            • I've updated the answer to real implementation. React will execute ref callback immediately after the component is mounted, so no need for onLoad on the image itself
              – felixmosh
              Sep 4 '17 at 9:01












            • why is the offsetHeight 0 though?
              – A. Lau
              Sep 4 '17 at 10:48















            up vote
            2
            down vote



            accepted











            React supports a special attribute that you can attach to any component. The ref attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted.



            When the ref attribute is used on an HTML element, the ref callback receives the underlying DOM element as its argument




            Taken from: https://facebook.github.io/react/docs/refs-and-the-dom.html






            class MyComponent extends React.Component {
            constructor(props) {
            super(props);
            }

            handleSize(image) {
            console.log(image.offsetWidth, image.offsetHeight)
            }

            render() {
            return React.createElement("img", {
            src: "http://cdn.collider.com/wp-content/uploads/2016/07/narcos-season-2-image-5.jpg",
            ref: image => {
            this.handleSize(image);
            }
            });
            }
            }

            ReactDOM.render(React.createElement(MyComponent, null), document.getElementById('root'))

            img {
            width: 200px;
            height: 133px;
            }

            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-with-addons.min.js">
            </script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

            <div id="root"></div>








            share|improve this answer























            • around the right idea, but it's returning 0 for both height and width. Tried to add an onLoad to it too but it didn't change the results :S
              – A. Lau
              Sep 4 '17 at 5:23










            • Please share your attempts
              – felixmosh
              Sep 4 '17 at 5:55










            • I might rename the question since it's more about onload.
              – A. Lau
              Sep 4 '17 at 8:41










            • I've updated the answer to real implementation. React will execute ref callback immediately after the component is mounted, so no need for onLoad on the image itself
              – felixmosh
              Sep 4 '17 at 9:01












            • why is the offsetHeight 0 though?
              – A. Lau
              Sep 4 '17 at 10:48













            up vote
            2
            down vote



            accepted







            up vote
            2
            down vote



            accepted







            React supports a special attribute that you can attach to any component. The ref attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted.



            When the ref attribute is used on an HTML element, the ref callback receives the underlying DOM element as its argument




            Taken from: https://facebook.github.io/react/docs/refs-and-the-dom.html






            class MyComponent extends React.Component {
            constructor(props) {
            super(props);
            }

            handleSize(image) {
            console.log(image.offsetWidth, image.offsetHeight)
            }

            render() {
            return React.createElement("img", {
            src: "http://cdn.collider.com/wp-content/uploads/2016/07/narcos-season-2-image-5.jpg",
            ref: image => {
            this.handleSize(image);
            }
            });
            }
            }

            ReactDOM.render(React.createElement(MyComponent, null), document.getElementById('root'))

            img {
            width: 200px;
            height: 133px;
            }

            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-with-addons.min.js">
            </script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

            <div id="root"></div>








            share|improve this answer















            React supports a special attribute that you can attach to any component. The ref attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted.



            When the ref attribute is used on an HTML element, the ref callback receives the underlying DOM element as its argument




            Taken from: https://facebook.github.io/react/docs/refs-and-the-dom.html






            class MyComponent extends React.Component {
            constructor(props) {
            super(props);
            }

            handleSize(image) {
            console.log(image.offsetWidth, image.offsetHeight)
            }

            render() {
            return React.createElement("img", {
            src: "http://cdn.collider.com/wp-content/uploads/2016/07/narcos-season-2-image-5.jpg",
            ref: image => {
            this.handleSize(image);
            }
            });
            }
            }

            ReactDOM.render(React.createElement(MyComponent, null), document.getElementById('root'))

            img {
            width: 200px;
            height: 133px;
            }

            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-with-addons.min.js">
            </script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

            <div id="root"></div>








            class MyComponent extends React.Component {
            constructor(props) {
            super(props);
            }

            handleSize(image) {
            console.log(image.offsetWidth, image.offsetHeight)
            }

            render() {
            return React.createElement("img", {
            src: "http://cdn.collider.com/wp-content/uploads/2016/07/narcos-season-2-image-5.jpg",
            ref: image => {
            this.handleSize(image);
            }
            });
            }
            }

            ReactDOM.render(React.createElement(MyComponent, null), document.getElementById('root'))

            img {
            width: 200px;
            height: 133px;
            }

            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-with-addons.min.js">
            </script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

            <div id="root"></div>





            class MyComponent extends React.Component {
            constructor(props) {
            super(props);
            }

            handleSize(image) {
            console.log(image.offsetWidth, image.offsetHeight)
            }

            render() {
            return React.createElement("img", {
            src: "http://cdn.collider.com/wp-content/uploads/2016/07/narcos-season-2-image-5.jpg",
            ref: image => {
            this.handleSize(image);
            }
            });
            }
            }

            ReactDOM.render(React.createElement(MyComponent, null), document.getElementById('root'))

            img {
            width: 200px;
            height: 133px;
            }

            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-with-addons.min.js">
            </script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

            <div id="root"></div>






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Sep 4 '17 at 20:44

























            answered Sep 4 '17 at 4:47









            felixmosh

            3,6022517




            3,6022517












            • around the right idea, but it's returning 0 for both height and width. Tried to add an onLoad to it too but it didn't change the results :S
              – A. Lau
              Sep 4 '17 at 5:23










            • Please share your attempts
              – felixmosh
              Sep 4 '17 at 5:55










            • I might rename the question since it's more about onload.
              – A. Lau
              Sep 4 '17 at 8:41










            • I've updated the answer to real implementation. React will execute ref callback immediately after the component is mounted, so no need for onLoad on the image itself
              – felixmosh
              Sep 4 '17 at 9:01












            • why is the offsetHeight 0 though?
              – A. Lau
              Sep 4 '17 at 10:48


















            • around the right idea, but it's returning 0 for both height and width. Tried to add an onLoad to it too but it didn't change the results :S
              – A. Lau
              Sep 4 '17 at 5:23










            • Please share your attempts
              – felixmosh
              Sep 4 '17 at 5:55










            • I might rename the question since it's more about onload.
              – A. Lau
              Sep 4 '17 at 8:41










            • I've updated the answer to real implementation. React will execute ref callback immediately after the component is mounted, so no need for onLoad on the image itself
              – felixmosh
              Sep 4 '17 at 9:01












            • why is the offsetHeight 0 though?
              – A. Lau
              Sep 4 '17 at 10:48
















            around the right idea, but it's returning 0 for both height and width. Tried to add an onLoad to it too but it didn't change the results :S
            – A. Lau
            Sep 4 '17 at 5:23




            around the right idea, but it's returning 0 for both height and width. Tried to add an onLoad to it too but it didn't change the results :S
            – A. Lau
            Sep 4 '17 at 5:23












            Please share your attempts
            – felixmosh
            Sep 4 '17 at 5:55




            Please share your attempts
            – felixmosh
            Sep 4 '17 at 5:55












            I might rename the question since it's more about onload.
            – A. Lau
            Sep 4 '17 at 8:41




            I might rename the question since it's more about onload.
            – A. Lau
            Sep 4 '17 at 8:41












            I've updated the answer to real implementation. React will execute ref callback immediately after the component is mounted, so no need for onLoad on the image itself
            – felixmosh
            Sep 4 '17 at 9:01






            I've updated the answer to real implementation. React will execute ref callback immediately after the component is mounted, so no need for onLoad on the image itself
            – felixmosh
            Sep 4 '17 at 9:01














            why is the offsetHeight 0 though?
            – A. Lau
            Sep 4 '17 at 10:48




            why is the offsetHeight 0 though?
            – A. Lau
            Sep 4 '17 at 10:48












            up vote
            0
            down vote













            i encountered the same issue, i was able to get the img height/width using refs and onLoad.



            render() {
            return (
            <img
            src='https://via.placeholder.com/150'
            ref={el = this.imgEl = el}
            onLoad={() => console.log(this.imgEl.naturalHeight)} // print 150
            />
            )
            }




            Also you should use img.naturalHeight






            share|improve this answer



























              up vote
              0
              down vote













              i encountered the same issue, i was able to get the img height/width using refs and onLoad.



              render() {
              return (
              <img
              src='https://via.placeholder.com/150'
              ref={el = this.imgEl = el}
              onLoad={() => console.log(this.imgEl.naturalHeight)} // print 150
              />
              )
              }




              Also you should use img.naturalHeight






              share|improve this answer

























                up vote
                0
                down vote










                up vote
                0
                down vote









                i encountered the same issue, i was able to get the img height/width using refs and onLoad.



                render() {
                return (
                <img
                src='https://via.placeholder.com/150'
                ref={el = this.imgEl = el}
                onLoad={() => console.log(this.imgEl.naturalHeight)} // print 150
                />
                )
                }




                Also you should use img.naturalHeight






                share|improve this answer














                i encountered the same issue, i was able to get the img height/width using refs and onLoad.



                render() {
                return (
                <img
                src='https://via.placeholder.com/150'
                ref={el = this.imgEl = el}
                onLoad={() => console.log(this.imgEl.naturalHeight)} // print 150
                />
                )
                }




                Also you should use img.naturalHeight







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited 18 hours ago

























                answered 20 hours ago









                Pierre Ferry

                11117




                11117






























                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f46030129%2freact-get-width-height-of-image-to-process%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest




















































































                    Popular posts from this blog

                    How to change which sound is reproduced for terminal bell?

                    Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

                    Can I use Tabulator js library in my java Spring + Thymeleaf project?