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>
);
}
One of the solution is to uplift and define the function of comp1 inside the parent component and then pass it to both the children comp1 and comp2.
This way comp2 and comp1 both can access the function.