Skip to main content

Command Palette

Search for a command to run...

An Interesting React Bug

Updated
2 min read

Sample Code:

Play around at https://codesandbox.io/p/devbox/an-intresting-react-error-d9gc2l, line 60.

Problem description:

When text area wrapped in a component, the text area would lose focus whenever user type in a character.

Some might ask what is the purpose of this Wrapper: DefaultRender, since we might have different render logic and design, we would like it to be dynamically rendered based on our needs (this part is removed from the code snippet, since it is unrelated to the bug).


// Here is a normal list rendering, the normal TextArea works perfectly fine, 
// but once replaced with the DefaultItemRender would trigger the problem of losing focus.
{editingItems.map((item, index) => {
  if (!item) return null;

  return (
    <div key={index}>
      {/* <TextArea
      value={item.title || ''}
      onChange={(value) => handleInputChange(index, 'title', value)}
    /> */}
      <DefaultItemRenderer
        item={item}
        index={index}
      />
    </div>
  );
})}

// Just a normal wrapper of TextArea, the reason for this wrapper is: initially 
const DefaultItemRenderer = ({ item, index }) => {
  return (
    <TextArea
      value={item.title || ''}
      onChange={(value) => handleInputChange(index, 'title', value)}
    />
  );
};


// TextArea is just a custom component
import React, { useRef, useEffect } from "react";

const TextArea = ({ value, onChange }) => {
  useEffect(() => {
    console.log("TextArea rendered");
  }, []);

  return (
    <textarea
      value={value}
      onChange={(e) => onChange(e.target.value)}
      rows={1}
    />
  );
};

export default TextArea;

Some guess around it:

Still confused about the cause.

An Interesting React Bug