Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

pass values and functions from a Child component to a Parent using a ref

// Parent Component
const App = () => {
  const ref = useRef();

  return (
    <div>
      <ComponentWithButton ref={ref} />
      <button onClick={() => ref.current.increment()}>another button</button>
    </div>
  );
};

// Child Component
const ComponentWithButton = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({increment}))

  const [count, setCount] = useState(0);
  const increment = () => setCount(count + 1);
  return (
    <div>
      <button onClick={increment}>click</button>
      <h2>Count: {count}</h2>
    </div>
  )
})
Source by dev.to #
 
PREVIOUS NEXT
Tagged: #pass #values #functions #Child #component #Parent #ref
ADD COMMENT
Topic
Name
5+6 =