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

162
Visualizações
How to avoid parent sending event to child in react

I have the following situation:

  • I have a component library with modal component. The modal already have action button implemented and when user click, it emits a click event.
  • This modal can be used to render one of couple of component inside of it.
  • I want to trigger an action related to the state of the child when user clicks on the action button
  • The modal also has a skip button that will switch the component inside of it

Modal graphic description

What i'm doing now is this: I have a component that accepts a key as a props, and from a pre-defined map, i will know the component i want to render (using React.lazy()), modal title, and action button text. It works, but this way i have to use my child's function when the action button is clicked (for example with using ref) but i want to avoid this, since it's not the react way.

export function MyModal(props: MyModalProps) {
  const {onClose, isOpen, key} = props;
  // custom hook that gives me the details for the render (including the component with React.lazy)
  const {
    title, subtitle, Component, actionText, changeKey, nextKey
  } = useModalRenderDetails(key);
  const handleModalHide = (event) => {
    onClose();
  };

  return (
    <Modal
      modalTitle={title}
      modalSubtitle={subtitle}
      mainActionLabel={actionText}
      secondaryActionLabel={'Skip'}
      open={isOpen}
      onHide={event => handleModalHide(event)}
      onMainAction={childHandlerFunctionFromRef}
      onSecondaryAction={() => changeKey(nextKey)}
    >
      <React.Suspense fallback={<div>LOADING</div>}>
        <Component/>
      </React.Suspense>
    </Modal>
  );
}

can anyone provide a better solution for this situation? Feel free to suggest design changes if needed

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This seems like a good usage of a context.

Context:

Consider placing the code below in a separate file and exporting only necessary items.

First of all, define a context:

const ConnectionContext = createContext();

Then create a custom provider to wrap the functions you need

const ConnectionContextProvider = ({ children }) => {
  const action = useRef(null);

  const setAction = (action) => {
    action.current = action;
  }

  const removeAction = () => {
    action.current = null;
  }

  const dispatchAction = () => {
    action.current && action.current()
  }

  return (
    <ConnectionContext.Provider
      value={{
        setAction,
        removeAction,
        dispatchAction,
      }}
    >
      {children}
    </ConnectionContext.Provider>
  );
}

Then wrap the useContext (this step is optional)

const useConnectionContext = () => {
  const context = useContext(context);
  return context;
}

Usage:

In the parent:

const MyModal = () => {
  const { dispatchAction } = useConnectionContext()
  // ...
  return (
    <Modal
      // ...
      onMainAction={dispatchAction}
    >
      // ...
    </Modal>
   )
}

In the child:

const Child = () => {
  const { setAction, removeAction } = useConnectionContext()

  useEffect(() => {
    setAction(() => {
      // the action you want to run
    })
    return () => removeAction()
  }, [])
}

Have in mind that all code in this answer is untested.

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