7

I have 4 instances of a certain React-class. After componentDidMount() I want to store the y-position of each instance.

How can I address the rendered element? I cannot use classname, because I have 4 elements of the same class with different positions.

My ReactJS component:

const Col = React.createClass({
    componentDidMount: function() {
        //here address the actual rendered col-instance
    },

    render() {
        return (
            <div className='col'>
            </div>
        );
    }
});
Kaloyan Kosev
  • 12,483
  • 8
  • 59
  • 90
vuvu
  • 4,886
  • 12
  • 50
  • 73
  • Just trying to understand the question more. Are you trying to store the y-position of each React component instance to use later? Also does the y-position of each of these elements change after mounting? – HussienK Dec 30 '16 at 15:42
  • I need to store it, it won't change. Maybe I can use this.ref ? – vuvu Dec 30 '16 at 15:44
  • 1
    Could you explain a little further what you are trying to achieve? Where do you want to store what? How do you want to access the stored values and from where? – Fabian Schultz Dec 30 '16 at 15:47
  • @FabianSchultz in the main-container there will be 4 -Elements, I want to store the y-pos of each in an array inside the Col-React-Class. – vuvu Dec 30 '16 at 15:51
  • So every `Col` element stores the `y` values of all `Col` elements? – Fabian Schultz Dec 30 '16 at 15:53

1 Answers1

14

Use refs.

First, hook-up a ref attribute on each of your JSX cols element. Then, use this ref, inside the componentDidMount method, to access the component's DOM node (the actual HTMLElement). Finally, get element's position / offset or anything else that you need.

const Col = React.createClass({
    componentDidMount: function() {
        // this.refs.col1 is the actual DOM element,
        // so you can access it's position / offset or whatever
        const offsetTop = this.refs.col1.offsetTop;
    },

    render() {
        return (
            <div className="col" ref="col1">
            </div>
        );
    }
});

PS: I am not sure what do you mean by saying element y position. Anyways, once you know how to get the DOM element (this.refs.col1), you can then use javascript to retrieve the position you need.

Community
  • 1
  • 1
Kaloyan Kosev
  • 12,483
  • 8
  • 59
  • 90
  • 3
    It was a good solution for older API of React.js. From https://reactjs.org/docs/refs-and-the-dom.html: "We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. " With new API here the solution: https://stackoverflow.com/questions/42242146/react-how-to-access-the-dom-element-in-my-render-function-from-the-same-compone – favero Oct 04 '17 at 17:45