Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
How to add an onClick to a parent from within React Component whose Ref is passed to it?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

function call: parentRef.current.onClick(onParentClick)

function assignment: parentRef.current.onclick = function

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!