react - how to expose property or method from your child component
to expose you can just use the following code. In this example, we are exposing a property called noOfEggs. Please note: this can be properties or method.
export const MyCounter = ({ noOfEggs }) => {
return (
<>
<button>Component prop drilling - {noOfEggs}</button>
</>
);
};
From the parent component
<MyCounter noOfEggs="3" />
You can achieve the same results via useRef/useImperativeHandle. To do this yiou need to declare useRef. Then you need to pass ref down to your child component as shown in the return block.
import { useRef } from 'react';
function App() {
const ref = useRef(null);
const handleClick = () => {
ref.current.someMethod();
};
return (
<>
<div></div>
<div className="card">
<MyCounterRef ref={ref} />
<button onClick={handleClick}>Click child's method</button>
</div>
</>
Then in your child component, you use useImperativeHandle and useState. As you can see here, the parents calls someMethod (belongs to the child) which in turn updates the count value. Apparently this should be avoided.
import React, { useImperativeHandle } from 'react';
import { useState } from 'react';
export const MyCounterRef = React.forwardRef((props, ref) => {
const [count, setCount] = useState(0);
console.log(props);
console.log(ref);
const someMethod = () => {
console.log(
'calling method from within a child comp. this could b e chaning the state of the child.'
);
setCount(count + 1);
};
useImperativeHandle(ref, () => ({
someMethod,
count,
}));
return (
<>
<button>Child component count: {count}</button>
</>
);
});
Comments