Response-redux get width of component parent div

This is part of the component:

import MyComp from '../../lib/MyComp'

const Data = ( { data } ) => (
    <div className="data-box" id="data-box">
        <MyComp data={data} />
    </div>
)

How to get data-boxdiv width inside MyComp container ?

+4
source share
3 answers

Check out this working demo: JSFiddle :

var Parent = React.createClass({
  render: function() {
    return <div id="parent">Hello Parent<Child></Child></div>;
  }
});

var Child = React.createClass({
  componentDidMount: function() {
    alert('Parent width: ' + this.refs.child.parentNode.clientWidth);
  },
  render: function() {
    return <div ref="child">Hello Child</div>;
  }
});

The article ref="child"will make the element accessible to the component itself through this.refs.child. This is an instance of vallina node. Using this.refs.child.parentNode.clientWidthwill return the parent width. Or use this.refs.child.parentNode.getBoundingClientRect().

Link: React refs

+6
source

You need to use reaction refs.

in your MyComp class:

class MyComp extends React.Component {

  //All your PropTypes and functions...

  //New function
  newFunction () {
    console.log(this.refs.refName);
    //This will give you the Data component. There you can call methods to calculate width, or whatever you need to do with that component
  }

  //Your render function
  render() {
    return <div ...whatever you have... ref="refName">
  }
}

+1

, - MyComp :

render() {
  return <div ref="node"></div>
}

with this.refs.nodeyou get the current dom element and

this.res.node.parentNode

you should get parentNode

0
source

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


All Articles