SolidJSS
SolidJSโ€ข2y agoโ€ข
13 replies
TripleSmile

How to use ref both inside and outside(parent) component?

I have parent component with this code:
return (
        <div>
            <div class="grid grid-cols-2 border gap-2 mx-auto min-w-[420px] max-w-[840px] px-4">
                {totalPrice()}
                <button onClick={() => myDialog?.showModal()}>Terms!</button>
            </div>

            <Dialog
                text="This is terms of service text text text, do you agree? 12354123135
            5645343 231E"
                ref={myDialog}
            />
        </div>
    );

And this is Dialog component:
  function Dialog(props) {
    return (
        <dialog
            onClick={() => {
                props.ref?.close();
            }}
            ref={props.ref}
            class="fixed inset-0 items-center justify-cente p-4"
        >
            <div
                onClick={(e) => e.stopPropagation()}
                class="border min-w-[420px] max-w-xl mx-auto bg-white p-1"
            >
                {props.text}
                <button
                    onClick={() => {
                        props.ref?.close();
                    }}
                >
                    Press me
                </button>
            </div>
        </dialog>
    );
}
export default Dialog;


So, I can open dialog from parent component because ref of dialog works as it should in the parent scope, but I can't use close() of ref of dialog element inside my Dialog component. What am I doing wrong? If I don't split this in two components then it works. But I would prefer to have this Dialog component separate and just be able to open it from a parent component.
Was this page helpful?