Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current element?

Tags:

reactjs

If I'm using something like this to set style:

<div style={this.setStyle()}>

  setStyle () {
    const style = {}
    if (this.state.fullScreen) {
      style.background = 'white'
      style.position = 'absolute'
      style.top = ???
    }
    return style
  }

How can I get the elements properties like .offsetLeft or .scrollLeft inside the funciton setStyle?

like image 466
Himmators Avatar asked Jan 05 '23 20:01

Himmators


1 Answers

Use refs.

First, hook-up a ref attribute on your JSX element:

<div ref="myElement" style={this.setStyle()}>

Then, use this ref inside the setStyle method, to access the component's DOM node (the actual HTMLElement) offsetLeft or scrollLeft or anything else that you need.

setStyle () {
  // ...

  // this.refs.myElement is the DOM element
  const offsetLeft = this.refs.myElement.offsetLeft;

  return style;
}
like image 98
Kaloyan Kosev Avatar answered Jan 07 '23 15:01

Kaloyan Kosev