I have this simple component that renders a link and a comment form. Clicking the link focuses the comment form. For that I use a ref that I create in the top level component and pass it down to the two sub-components. This part works fine.
import { useRef } from "react";
export default function Commentable({children}) {
const textareaRef = useRef();
return (
<>
<CommentableButton formRef={textareaRef} />
<CommentForm formRef={textareaRef} />
</>
)
}
export function CommentableButton({formRef}) {
function focusForm(e) {
e.preventDefault();
formRef.current.focus();
}
return (
<a href="#" onClick={focusForm}>Comment</a>
)
}
export function CommentForm({formRef}) {
return (
<textarea ref={formRef}></textarea>
)
}
I want to be able to pass CommentButton and CommentForm down to children like this:
export default function Commentable({children}) {
const textareaRef = useRef();
return (
{children
button={<CommentableButton formRef={textareaRef} />}
form={<CommentForm formRef={textareaRef} />}
}
)
}
so I can use it like this:
<Commentable>
<div class="card">
<div class="card-body">
<h5>Media Title</h5>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur nec enim id dolor elementum imperdiet. Phasellus luctus ante elit, ac egestas diam posuere at.</p>
<hr />
{button}
</div>
<div class="card-footer">
{form}
</div>
</div>
<Commentable>
There are many commentable entities in the app that I'm building and I'd like to keep all the commentable behavior located in one component that I can use when needed. I've tried different ways of achieving this, but can't seem to figure it out. I'm pretty new to React and just getting started with it. Please let me know if there's a better way to do this. I'm trying to do this just with function components and hooks. Thanks for any help!