Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: onChange Text setProp many times #731

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions examples/landing/components/selectors/Text/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useNode, useEditor } from '@craftjs/core';
import React from 'react';
import React, { useCallback, useRef } from 'react';
import ContentEditable from 'react-contenteditable';

import { TextSettings } from './TextSettings';
Expand Down Expand Up @@ -30,13 +30,26 @@ export const Text = ({
const { enabled } = useEditor((state) => ({
enabled: state.options.enabled,
}));
const textRef = useRef(text);

const decodeHTML = useCallback((str: string) => {
const div = document.createElement('div');
div.innerHTML = str;
return div.textContent || '';
}, []);
return (
<ContentEditable
innerRef={connect}
html={text} // innerHTML of the editable div
disabled={!enabled}
onChange={(e) => {
setProp((prop) => (prop.text = e.target.value), 500);
// Avoid calling setProp many times
const newText = e.target.value;

if (decodeHTML(newText) !== decodeHTML(textRef.current)) {
textRef.current = newText;
setProp((prop) => (prop.text = newText), 500);
}
}} // use true to disable editing
tagName="h2" // Use a custom HTML tag (uses a div by default)
style={{
Expand Down