Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Child Element's DOM Node in React

I am working with React & SVG.

In order to centre the viewbox on the child <g>, I need to get the 'BBox' value by calling the getBBox() API function on the child <g> element. My code looks like this:

// <SVG> Element
const SVGParent = React.createClass({
    componentDidMount : function(){
    let eleBBox = ReactDOM.findDOMNode( this.refs.gEle ).getBBox();
...

// Child <g> Element
const TemplateParent = React.createClass({
   render : function(){
      return(
         <g ref = "gEle">
...

The above line let eleBBox = ReactDOM.findDOMNOde( this.refs.gEle ) returns error: TypeError: _reactDom2.default.findDOMNode(...) is null

And indeed, the this.refs inside 'SVG' element is empty obj. How do I access the child <g> element, so I can access its DOM node?

Thanks,

like image 316
Kayote Avatar asked Jul 09 '26 03:07

Kayote


1 Answers

You can chain refs to reach further down a component hierarchy if need be:

// Parent Element
componentDidMount: function() {
  let eleBBox = this.refs.templateRef.refs.gEle;
}

// Adding a ref to your child component
<TemplateParent ref='templateRef' ... />

But this can get a little unwieldy and isn't usually suggested. Refs should typically be treated as private to their component, since accessing them in this way weirdly makes the parent dependent on the naming schemes of its child.

A more common alternative is to expose a function on the child component:

const Parent = React.createClass({
  componentDidMount: function() {
    let eleBBox = this.refs.svgRef.getG();
  }

  render: function() {
    return(
      <Child ref='svgRef' />
    );
  }
}

const Child = React.createClass({
  getG: function() {
    return this.refs.gEle;
  }

  render: function() {
    return(
      <svg ...>
        <g ref='gEle' ...>
          <circle .../>
          <circle .../>
        </g>
      </svg>
    );
  }
}

Here's a working DEMO so you can check it out + DOCS for reference.

like image 89
Brad Colthurst Avatar answered Jul 11 '26 19:07

Brad Colthurst



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!