Code:
import DrawControl from "react-mapbox-gl-draw"; export default function MapboxGLMap() { let drawControl = null return( <DrawControl ref={DrawControl => {drawControl = DrawControl}}/> ) }
I want to load data when the drawControl
not null. I check the document that may use callback ref.
So, how do I listen the drawControl
changes and load data?
And since changing ref doesn't cause the component to re-render, the button stays active. To demonstrate this point further, let's add a parent component. By default when you render a React component it recursively re-renders all its children.
[2:52] In summary, useRef can be used to store data values just like useState, but the difference is that when that value changes, it doesn't cause a re-render.
Forcing an update on a React class component In any user or system event, you can call the method this. forceUpdate() , which will cause render() to be called on the component, skipping shouldComponentUpdate() , and thus, forcing React to re-evaluate the Virtual DOM and DOM state.
If you want to trigger a re-render after the ref changes, you must use useState
instead of useRef
. Only that way can you ensure that the component will re-render. E.g.:
function Component() { const [ref, setRef] = useState(); return <div ref={newRef => setRef(newRef)} /> }
As described under useRef documentation:
Keep in mind that
useRef
doesn’t notify you when its content changes. Mutating the.current
property doesn’t cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.
It may sometimes be better to store whatever value you are getting from the DOM node, as suggested here, instead of storing the node itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With