'React.forwardRef - get value from child component

Imagine we have code like this:

const InputComponent = React.forwardRef((props, ref) => {
  // I need to access ref.current?.value... here
  return <input ref={ref} {...props} />
})

const Parent = () => {
  const inputRef = useRef()


  return <InputComponent ref={ref} />
}

This technique seems to be impossible? the typeof ref in InputComponent is a function but cannot be called. Can I access the ref.current.value from InputComponent?



Solution 1:[1]

Except a typo your code should work, the only thing to notice that you don't have the ref on first render therefore the optional chaining current?.value.

And because its a ref, changing the input value does not trigger a render, so to debug its value you need manually trigger it.

import "./styles.css";
import React, { useReducer, useRef } from "react";

const InputComponent = React.forwardRef((props, ref) => {
  console.log(ref.current?.value);
  return <input ref={ref} {...props} />;
});

const Parent = () => {
  const inputRef = useRef();
  const [, render] = useReducer((p) => !p, false);

  return (
    <>
      <InputComponent ref={inputRef} />
      <button onClick={render}>trigger render to see ref value</button>
    </>
  );
};

export default function App() {
  return <Parent />;
}

Edit objective-bouman-e75or

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dennis Vash