Just like the title says, I've got 2 custom components on a page in a simple NextJS application:
<section>
<CompA></CompA>
<CompB></CompB>
</section>
How can I have a button in CompB trigger a function contained in CompA?
I assume I should use state somehow, but I'm a little lost how to do that in NextJS. Simple code example here: https://github.com/Chenzo/nextjs-comp-to-comp
Technically, you can do this with the useImperativeHandle hook, but this is not exactly the "React way":
const CompA = forwardRef(({ children }, ref) => {
useImperativeHandle(ref, () => ({
doSmth: () => {
console.log('CompA - function');
},
}));
return (
<div>
<h2>Component A</h2>
</div>
);
});
const CompB = ({ onClick }) => {
return (
<div>
<h2>Component B</h2>
<button onClick={onClick}>Trigger CompA function</button>
</div>
);
};
export default function Home() {
const compARef = useRef();
const handleCompBClick = useCallback(() => compARef.current?.doSmth(), []);
return (
<section>
<CompA ref={compARef}></CompA>
<CompB onClick={handleCompBClick}></CompB>
</section>
);
}
As I wrote above, there is most likely a more correct way to solve your problem, avoiding the imperative approach. The decision will depend on what exactly components A and B will do in a real application.