Skip to main content

Hashtags

Hashtags plugin can be used to add hashtags dropdown to the editor. The dropdown will be opened when the user types # followed by a letter. The dropdown will show the hashtags that start with the letter that the user typed.

Result
Loading...
const Demo = () => {
  const [hashtags, setHashtags] = useState([
    {
      value: "react",
      label: "React",
    },
    {
      value: "javascript",
      label: "JavaScript",
    },
    {
      value: "typescript",
      label: "TypeScript",
    },
    {
      value: "html",
      label: "HTML",
    },
    {
      value: "css",
      label: "CSS",
    },
  ]);

  return (
    <Editor nodes={[HashTagNode]}>
      <EditorToolbar />
      <RichEditor
        editorContainerProps={{
          css: {
            ".editor-container .editor": {
              ".twigs-hashtag": {
                backgroundColor: "$primary100",
                display: "inline-block",
                borderRadius: "$md",
                padding: "0 $2",
              },
            },
          },
        }}
      />
      <HashTagPlugin
        getResults={(searchString) => {
          /**
           * Find existing hashtags that match the search string
           */
          const searchResults = hashtags.filter((hashtag) =>
            hashtag.value
              .toLowerCase()
              .includes((searchString || "").toLowerCase())
          );

          /**
           * If the search string is not found in the existing hashtags, add it as a new hashtag
           */
          if (!searchResults.find((hashtag) => hashtag.value === searchString)) {
            searchResults.unshift({
              value: searchString,
              label: searchString,
              isNew: true
            });
          }
          return searchResults;
        }}
        onMenuItemSelect={(item) => {
          /**
           * If the selected item is a new hashtag, add it to the list of hashtags
           */
          if (item.data.isNew) {
            setHashtags((prev) => [
              ...prev,
              {
                value: item.data.value,
                label: item.data.value,
              },
            ]);
          }
        }}
      />
    </Editor>
  );
};

render(<Demo />);