Search code examples
javascriptreactjsjsxreact-dom

ReactDOM.findDOMNode with getAttribute("") returns null


I am defining tooltip as

<MACDTooltip ref="MACDTooltip" forChart={chartId} forDataSeries={dataSeriesId} key={`${chartId}-${dataSeriesId}`} calculator={macdCalculator}
                onClick={logger.bind(null, { chartId, dataSeriesId }, options)} origin={[-48, 15]}/> 

but in componentDidMount() method

ReactDOM.findDOMNode(this.refs.MACDTooltip).getAttribute("transform")

return null

ReactDOM.findDOMNode(this.refs.MACDTooltip)

returns

 <g><g class="react-stockcharts-toottip" transform="translate(-48, 15)"...</g></g>

and

ReactDOM.findDOMNode(this.refs.MACDTooltip).innerHTML

return "<g class="react-stockcharts-toottip" transform="translate(-48, 15)"></g>

How do i use ReactDOM.findDOMNode to get proper value


Solution

  • Since the g tags are nested, you want to find the childNode of it and get the attribute from there. Example:

    class Example extends React.Component {
      componentDidMount() {
        console.log(
          ReactDOM.findDOMNode(this.refs.MACDTooltip).childNodes[0].getAttribute('transform')
        );
      }
      render() {
        return(
          <MACDTooltip ref="MACDTooltip" />
        );
      }
    }
    
    // Sample MACDTooltip class for demo.
    class MACDTooltip extends React.Component {
      render() {
        return(
          <g>
            <g transform="Attribute"><text>Tooltip</text></g>
          </g>
        );
      }
    }
    
    ReactDOM.render(<Example />, document.getElementById('View'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="View"></div>