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>
);
}
});
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.
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.
props is available in the entire class.
There is some fundamental misunderstanding here, you can still call the functions inside componentDidMount , however you should not define them inside it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With