I'm transitioning from create react app to next.js. I'm just getting firmiliar with useRef and I can't figure out how to use a Ref as a dom node to reder a modal into.
function TableDate(props: any) {
const [showModal, setShowModal] = useState(false);
let uuid = props.uuid;
let today = props.today;
let dist = props.dist;
//let modalParent = document.getElementById(`${dist}-${uuid}`);
const modalRef = useRef()
const ref = useRef();
useOnClickOutside(ref, () => setShowModal(false));
return (
<>
<td ref={ modalRef } id= {`${dist}-${uuid}`} className = {`overflow-visible border-t border-black ${uuid} `}>
<button onClick={ () => setShowModal(true) } className = {`px-2 border-black border rounded-full m-2 w-min btn-${uuid}`}> { today } </button>
</td>
{
showModal && createPortal(
<div ref={ ref } >
<Fun abc={ uuid } onClose = {() => setShowModal(false)}/>
</div>,
modalRef
)
}
</>
)
}
this function is supposed render table data with a button which value is the day of the month and when clicked creates a modal where you clicked.
when i click on the button i receive
Unhandled Runtime Error
Error: Target container is not a DOM element.
(the line commented out line is how i done it when using create react app)
im also refrencing a function that uses document
//imported function from stackOverflow
function useOnClickOutside(ref, handler) {
useEffect(
() => {
const listener = (event) => {
// Do nothing if clicking ref's element or descendent elements
if (!ref.current || ref.current.contains(event.target)) {
return;
}
handler(event);
};
document.addEventListener("mousedown", listener);
document.addEventListener("touchstart", listener);
return () => {
document.removeEventListener("mousedown", listener);
document.removeEventListener("touchstart", listener);
};
},
// Add ref and handler to effect dependencies
// It's worth noting that because the passed-in handler is a new ...
// ... function on every render that will cause this effect ...
// ... callback/cleanup to run every render. It's not a big deal ...
// ... but to optimize you can wrap handler in useCallback before ...
// ... passing it into this hook.
[ref, handler]
);
}
this function closes the modal on a click outside the modal
its from Closing a modal on clicking outside it with React Hooks