How to get the ReactJS element inside componentDidMount ()?

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

How can I access the rendered element? I cannot use the class name 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>
        );
    }
});
+4
source share
1 answer

Use refs .

First, include an attribute reffor each JSX cols element. Then use ref, inside the method componentDidMount, to access the DOM node component (actual HTMLElement). Finally, get the position / offset of the element or something else you need.

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

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

PS: , , element y. , , DOM (this.refs.col1), javascript .

+5

Source: https://habr.com/ru/post/1665346/


All Articles