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

149
Visualizações
Can a (modern) React functional component expose a stateful method externally?

Can my React functional component expose externally a method with access to internal state?

interface Inner {
  foo: string
}

function Inner(props: Inner) {
  const [foo, setFoo] = useState<string>(props.foo + "baz")
    
  function doTheThing() {
    console.log(`doin' that ${foo} thing`)
  }

  return <div>{props.foo}</div>
}

function Outer() {
  const inner = <Inner foo="bar" />

  return (
    <>
      <button onClick={() => inner.doTheThing()}>
        Do That Thing
      </button>
      {inner}
    </>
  )
}

This of course gives me an error: TypeError: inner.doTheThing is not a function.

I can use a class component to expose a method like this. But is there a way (with hooks? with refs?) to make this work with a functional component?

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

0

You can pass a ref, and then store doTheThing reference there.

import { MutableRefObject, useRef, useState } from "react";

interface Inner {
  foo: string;
  dRef: MutableRefObject<{ doTheThing: () => void } | undefined>;
}

function Inner(props: Inner) {
  const [foo, setFoo] = useState<string>(props.foo + "baz");

  function doTheThing() {
    console.log(`doin' that ${foo} thing`);
  }

  props.dRef.current = { doTheThing };

  return <div>{props.foo}</div>;
}

export function Outer() {
  const dRef = useRef<{ doTheThing: () => void }>();
  const inner = <Inner foo="bar" dRef={dRef} />;

  return (
    <>
      <button onClick={() => dRef.current?.doTheThing()}>Do That Thing</button>
      {inner}
    </>
  );
}
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