Reputation: 681
I have this component
const Pubs = () => {
const selectArea = useRef<HTMLInputElement | null>(null);
return (
<LikesComments selectArea={selectArea} publication={publication} />
<DisplayComments selectArea={selectArea} publication={publication} />
</PubHero>
);
};
export default Pubs;
And, when i pass the useRef to likesComments, i have this function who will use the useRef as props
interface IlikesCommentsProps {
selectArea: Idontknow
}
const LikesComments: React.FC<IlikesCommentsProps> = ({ selectArea }) => {
const focusComment = () => {
selectArea.current.focus()
}
return (
<div onClick={focusComment}>
<CommentIcon />
<LikeCommentText separation='0.7rem'>Comentar</LikeCommentText>
</div>
)
}
export default LikesComments
And when i click that function in the first comment, i want it to focus an input (textarea) in the second component
interface IcreateComments {
selectArea: Idontknow
}
const CreateComments: React.FC<IcreateComments> = ({ selectArea }) => {
return <textarea ref={selectArea} />
}
export default CreateComments
How can i make this happen?
I really haven't tried before to pass useRef as props, so, i really don't know what to do exactly, i've tried to look for answers, but found nothing at all
Can you help me with this?
Thanks for your time!
Upvotes: 0
Views: 1007
Reputation: 4723
There are many ways to do it. I am showing one.
Firstly you can use a single ref for that. Just you have to take help of an menthod. The method will focus to the textarea.
const handleSelectArea = () => {
selectArea.current.focus()
}
Now pass them to the two component that you want
<LikesComments handleSelectArea={handleSelectArea} publication={publication} />
Inside the component onCLick
call the method
const focusComment = () => {
handleSelectArea();
};
As you are already passing the ref to the text area so it will focus that.
You have to use the ref as bellow
type TextareaProps = React.HTMLProps<HTMLTextAreaElement>
const CreateComments = React.forwardRef<HTMLTextAreaElement, TextareaProps>((props, ref) => {
return <textarea ref={ref}/>
})
Upvotes: 1