Monday, 28 June 2021

update dom ref using d3 and react

I have a functional component with a d3 function which appends a p to the ref on mount

Im trying to change the text content of the appended paragraph using the useState hook

clicking the button <button type="button" onClick={(e)=> setData("bar")}>change data</button> triggers a re-render, instead of changing the text of the p tag , a new version of the d3 function gets created --> appends a new p

reading How to rerender when refs change suggest to use the useCallback hook which im not quit sure how implement

how to achive a a re-render of the paragraph without creating a new one?

import {useEffect, useState, useRef} from 'react'

import * as d3 from 'd3'

function DomReference() {

  const domRef = useRef()

  const [data, setData] = useState("foo")

  useEffect(()=>{


    d3.select(domRef.current)
      .append('p')
      .text(data)
    
    // re-render --> creates a new function 
    
  }, [data])


  return (
    <div ref={domRef}>
      <button type="button" onClick={(e)=> setData("bar")}>change data</button>
      
    </div>
  )
}

export default DomReference



from update dom ref using d3 and react

No comments:

Post a Comment