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

338
Visualizações
Getting TypeError when I'm passing a Ref from a function component to other function component using forwardRef in react js,

I want to pass the ref from the App to Foo, App and Foo are function components, so I'm using forwardRef() to warp the Foo, but I get the error warning TypeError: Cannot add property current, object is not extensible. Below id my code, we do I need to change?

import './App.css';
import React, { useState, Component, useEffect, createRef, useRef, forwardRef } from 'react'
import ReactDOM from 'react-dom'

const Foo=forwardRef((inputRef)=> {
  const onClick = () => {
    inputRef.current.focus()
  }
    return (
      <div>
        <input type="text" ref={ inputRef }></input>
        <button onClick={ onClick }>Focus</button>
      </div>
    ) 
})
function App() {
  const inputRef = createRef()
  const clicked = () => {
    inputRef.current.focus()
  }
  return (
    <div>
      <Foo ref={inputRef} />
      <button onClick={ clicked }>Click Foo</button>
    </div>
  )
  
}
export default App;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Please define ref at start function

const inputRef = useRef(null); 
about 4 years ago · Juan Pablo Isaza Relatório

0

Ref Forwarding receives two parameters props and ref.

React.forwardRef((props, ref) =>{
    return(
        <button ref={ref}>{props.children}</button>
    )
};

Here is your edited code I've added type for ref which is HTMLInputElement.

type RefType = HTMLInputElement | null;
interface PropsType {}

const Foo = forwardRef<RefType, PropsType>((props, ref) => {
  const onClick = () => {
   if (ref && "current" in ref) {
    ref.current?.focus();
   }
};
  return (
     <div>
       <input type="text" ref={ref}></input>
       <button onClick={onClick}>Focus</button>
     </div>
 );
});

 function App() {
  const inputRef = createRef<HTMLInputElement>();
  const clicked = () => {
  inputRef.current?.focus();
 };
  return (
     <div>
     <Foo ref={inputRef} />
     <button onClick={clicked}>Click Foo</button>
    </div>
   );
  }
 export default App;
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