Skip to content

Instantly share code, notes, and snippets.

@antishok
Created December 24, 2021 01:01
Show Gist options
  • Save antishok/6a0f5e85bfbae615d360fdff8c167c9f to your computer and use it in GitHub Desktop.
Save antishok/6a0f5e85bfbae615d360fdff8c167c9f to your computer and use it in GitHub Desktop.
react-activity-feed Comment Reply Field
import React, { useRef, useState, useEffect } from 'react';
import classNames from 'classnames';
import { useFeedContext, useTranslationContext, Textarea, Button, Avatar } from 'react-activity-feed';
export const CommentReplyField = ({
comment,
emojiData,
onSuccess,
image,
placeholder,
trigger,
targetFeeds,
className,
style,
}) => {
const feed = useFeedContext();
const { t } = useTranslationContext();
const textareaReference = useRef<HTMLTextAreaElement>(undefined);
const [text, setText] = useState(undefined);
const handleFormSubmit = async (event) => {
event.preventDefault();
if (!text) return;
try {
await feed.onAddChildReaction('comment', comment.id, {text}, {targetFeeds});
} catch (error) {
console.error(error);
}
setText('');
if (onSuccess) { onSuccess(); }
};
useEffect(() => {
if (!textareaReference.current) return;
const handleFormSubmitKey = (event) => {
const { current: textarea } = textareaReference;
if (event.key === 'Enter' && textarea?.nextSibling === null) {
handleFormSubmit(event);
}
};
textareaReference.current.addEventListener('keydown', handleFormSubmitKey);
return () => textareaReference.current?.removeEventListener('keydown', handleFormSubmitKey);
}, []);
return (
<form onSubmit={handleFormSubmit} className={classNames('raf-comment-field', className)} style={style}>
{image && <Avatar image={image} circle size={39} />}
<div className="raf-comment-field__group">
<Textarea
rows={1}
value={text}
placeholder={placeholder ?? t('Start Typing...')}
onChange={(event) => setText((pv) => event.target.value ?? event.currentTarget.value ?? pv)}
emojiData={emojiData}
trigger={trigger}
maxLength={280}
innerRef={textareaReference}
/>
<Button buttonStyle="primary" disabled={!text} type="submit">
{t('Post')}
</Button>
</div>
</form>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment