I have a div inside reactstrap Modal, I want to call my function which grab's this div's attribute (after it has been rendered). I have tried useEffect
on modalShow
, I have tried useRef on that div, I have tried calling the function inside the div.
<div
custom-attribute="VALUE"
ref={modalRef}
>
{handleModalLoad()}
</div>
But the problem is that my function i.e. handleModalLoad()
gets executed before the modal is rendered therefore I am unable to grab the value from this attribute.
CodePudding user response:
<div
custom-attribute="VALUE"
ref={modalRef}
>
{handleModalLoad()}
</div>
yes in this way your function will run irrespective of latest ref
value.
do this
const someRef=useRef(null)
useEffect(()=>{
handleModalLoad()
},[someRef])
{
isModalOpen && <div
custom-attribute="VALUE"
ref={someRef}
>
</div>
}
CodePudding user response:
Try make the custom div a component and use useEffect
inside to send the value out.
Without dependency array, useEffect
will only run when this component renders. You can get the value with useRef
and send it out with a callback function inside useEffect
.
You can reuse this component if you need to get any attribute value in another modal as well.
Example: (also check out the live demo: stackblitz)
import React, { useState, useEffect, useRef } from 'react';
export function MyDiv({ handleModalLoad }) {
const myDivRef = useRef(null);
//