Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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 Respostas
Responde à pergunta

0

function call: parentRef.current.onClick(onParentClick)

function assignment: parentRef.current.onclick = function

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda