Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get element margin in React JS

I'm trying to create an slider in React.

My component is as follows :

outterDivStyles() {
        return {
            position: "relative",
            width: "100%",
            overflow: "hidden",
            height: this.props.height || 200
        }
    }

innerDivStyles(){
    return {
        position: "absolute",
        top: 0,
        left: this.state.left,
        right: 0,
        width: "1000%",
        transition: "left .5s",
        transitionTimingFunction: "ease"
    }
}

renderArrows(){
    return (
        <div className="next-prev" style={{height: this.props.height || 200}}>
            <div onClick={this.prevSlide.bind(this)}><img src={images.slider_arrow_left_png} /></div>
            <div onClick={this.nextSlide.bind(this)}><img src={images.slider_arrow_right_png} /></div>
        </div>
    )
}


render(){
return(
<div>
    <div ref="detailsOutterDiv" className="detailsOutterDiv" style={this.outterDivStyles()}>
         <div ref="detailsInnerDiv" className="detailsInnerDiv" style={this.innerDivStyles()}>
              {this.carInfo().photos.map((p, i) => {
                  return (
                      <div key={i} className="slide"><img src={p.image_url}/></div>
                  );
               })}
         </div>
         {this.renderArrows()}
    </div>
</div>
)
}

The css is as follows :

.slide{
  margin-right: 15px;
  display: inline-block;
}

.slide img{
  width: 100%;
  height: auto;
}


@media (min-width: 1599px) {
  .detailsOutterDiv .detailsInnerDiv div{
    width: (10% / 3);

  }
}

Now I'm trying to get width plus margin of the div with class slide.

I try to do it with :

let slideWidth = this.refs["detailsInnerDiv"].childNodes[0].style.marginRight;

But slideWidth is 0.

Any advice?

like image 351
Boky Avatar asked Oct 19 '25 09:10

Boky


1 Answers

Try this.

let node = this.refs["detailsInnerDiv"].childNodes[0] //assuming this as your target node
let nodeStyle = window.getComputedStyle(node)
let slideMarginRight = nodeStyle.getPropertyValue('margin-right')

For more info refer MDN

Hope this helps!

like image 191
Pranesh Ravi Avatar answered Oct 21 '25 21:10

Pranesh Ravi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!