I am working on a Reusable Menu Component.
It takes an array of objects and generates the Menu based on the array sent as prop.
This menu will always be triggered on click.
Now what I wanted to do is have the onClick implementation(event listeners, onClick function, etc) inside the Menu component itself.
How I planned on doing it was assigning a Ref to whatever is the Parent of the menu(the element that needs to be clicked for the menu to show) and sending that ref down to Menu and using the Ref to attach the onClick function onto the parent.
Parent.jsx
import React, {useRef} from 'react';
const Parent = () => {
const menuRef = useRef(null);
return(
<>
{/*
A lot of elements
*/}
<ul type="none">
<li>Some svg's in a list</li>
.
.
.
<li ref={menuRef}>
<svg>Another svg...</svg>
<Menu parentRef={menuRef} items={menu} />
</ul>
</>
)
}
Menu.jsx
import React, {useState} from 'react';
const Menu = ({parentRef,items}) => {
const [isMenuActive, setMenuActive] = useState(false);
const onParentClick = (e) => {
// some code and then
setMenuActive(!isMenuActive);
}
// This is what I intended to do
parentRef.current.onClick(onParentClick);
return(
<div className={`menu-container ${isMenuActive ? 'active' : '' }`}
{/*
Menu population code
*/}
</div>
)
}
The problem is every function of parentRef.current.* is returning null.
A console.log of parentRef is yielding an object with the current havin the entire <li> tag as expected. But I am not getting how to assign an onClick onto it.
Any help is appreciated.
function call: parentRef.current.onClick(onParentClick)
function assignment: parentRef.current.onclick = function