Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the ReactJS element inside componentDidMount()?

Tags:

reactjs

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>
        );
    }
});
like image 599
vuvu Avatar asked Dec 30 '16 15:12

vuvu


People also ask

How do you get elements in React?

In React we can access the DOM element using Refs. Refs provide a way to access DOM nodes or React elements created in the render method. Creating Refs: Refs are created using React. createRef() and attached to React elements via the ref attribute.

What do you usually do in componentDidMount ()?

The componentDidMount() method allows us to execute the React code when the component is already placed in the DOM (Document Object Model). This method is called during the Mounting phase of the React Life-cycle i.e after the component is rendered.

Are Props available in componentDidMount?

props is available in the entire class.

Can I call componentDidMount in a function?

There is some fundamental misunderstanding here, you can still call the functions inside componentDidMount , however you should not define them inside it.


1 Answers

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.

like image 96
Kaloyan Kosev Avatar answered Sep 27 '22 22:09

Kaloyan Kosev