My parent component looks like
<Tabs tabs={[
{
id: "Comp1",
content: (
<Comp1/>
),
},
{
id: "Comp2",
content: (
<Comp2/>
),
},
]}
/>
The requirement is to execute a function in comp1 on a button click in comp2 ?
What is the best way to handle such situations?
I am not much inclined towards handling it through redux-store, and have doubts over passing it through props
Here is example, in this scenario, Child will execute some function (which focuses an input) from FancyInput component, when clicking the div.
function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focusInput: () => {
inputRef.current.focus();
},
}));
return <input ref={inputRef} />;
}
FancyInput = forwardRef(FancyInput);
let Child = (props) => {
return <div onClick={props.callback}>Hello</div>;
};
export default function App() {
let inputRef = useRef();
let callback = () => inputRef.current.focusInput();
return (
<div>
<FancyInput ref={inputRef} />
<Child callback={callback} />
</div>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With