Tamjid
Tamjid

Reputation: 5546

Replace findDOMNode with ref

Can someone please help me understand how to use ref in place of findDOMNode? I'm trying to reference a d3 object and originally did so using findDOMNode but I'm getting warning that this is deprecated. Please see my code below:

class Node extends Component {
  componentDidMount() {
    this.d3Node = d3.select(ReactDOM.findDOMNode(this))
      .datum(this.props.data)
      .call(FORCE.enterNode)
  }

  componentDidUpdate() {
    this.d3Node.datum(this.props.data)
      .call(FORCE.updateNode)
  }

  render() {
    return (
      <g className='node'>
        <circle onClick={this.props.addLink}/>
        <text>{this.props.data.name}</text>
      </g>
    );
  }
}

export default Node;

Thanks

Upvotes: 1

Views: 2632

Answers (1)

user120242
user120242

Reputation: 15268

How to use refs docs: https://reactjs.org/docs/refs-and-the-dom.html

class Node extends React.Component {
  constructor(props) {
    super(props)
    this.gRef = React.createRef()
  }
  componentDidMount() {
    this.d3Node = d3.select(this.gRef.current)
      .datum(this.props.data)
      .call(FORCE.enterNode)
  }

  componentDidUpdate() {
    this.d3Node.datum(this.props.data)
      .call(FORCE.updateNode)
  }

  render() {
    return (
      <g className='node' ref={this.gRef}>
        <circle onClick={this.props.addLink}/>
        <text>{this.props.data.name}</text>
      </g>
    );
  }
}

export default Node;

Upvotes: 4

Related Questions