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 ie handleModalLoad()
gets executed before the modal is rendered therefore I am unable to grab the value from this attribute.
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);
// 👇 only run when this component renders
useEffect(() => {
// 👇 get value from custom attribute
const { customAttribute } = myDivRef.current.dataset;
if (!customAttribute) return;
// 👇 run the function needed
handleModalLoad(customAttribute);
}, []);
return (
<div data-custom-attribute="VALUE" ref={myDivRef}>
<h2>This is my div in modal</h2>
</div>
);
}
export default function App() {
const [modalOpen, setModalOpen] = useState(false);
const [myValue, setMyValue] = useState('');
return (
<>
<div>
<h1>{`Click button to get: ${myValue}`}</h1>
<button onClick={() => setModalOpen(true)}>OPEN MODAL</button>
{modalOpen && <MyDiv handleModalLoad={(value) => setMyValue(value)} />}
</div>
</>
);
}
Hope this will help!
<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>
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.