Kayote
Kayote

Reputation: 15617

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,

Upvotes: 3

Views: 6421

Answers (2)

Brad Colthurst
Brad Colthurst

Reputation: 2605

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.

Upvotes: 4

omarjmh
omarjmh

Reputation: 13888

If you put a ref on a child you can get it in the parent like so, no need to look for the DOM node:

const SVGParent = React.createClass({
    componentDidMount : function(){
    let eleBBox = this.refs.gEle
    ...

Upvotes: 1

Related Questions