Next.js Discord

Discord Forum

useState not working

Unanswered
Sloth bear posted this in #help-forum
Open in Discord
Sloth bearOP
I have a placeholder and I only want to display it if the user is not focused, or if the content is empty. Currently the logic should be working, but it isn't bcause of the way that states update. What should I do?

  const [content, setContent] = useState('');
  const [isPlaceholderVisible, setIsPlaceholderVisible] = useState(true);

  const handleContentChange = (e: React.ChangeEvent<HTMLDivElement>) => {
    setContent(e.target.textContent || '');
  }

  const handleContentFocus = () => {
    setIsPlaceholderVisible(false);
  }

  <div
    className={`outline-none mt-4 ${isPlaceholderVisible ? 'text-accent' : ''}`}
    contentEditable
    onFocus={handleContentFocus}
    onBlur={() => setIsPlaceholderVisible(content === '')}
    onChange={handleContentChange}
  >
  {isPlaceholderVisible ? 'Start typing...' : content}
  </div>

0 Replies