Home > Software design >  Why can't I append a child using useState in React?
Why can't I append a child using useState in React?

Time:07-21

I am using React and found something which was not quite working, but it made sense to me totally:

const [Res, setRes] = useState(<div></div>);
const test = (e) => {
    if (e.keyCode === 13) {
      setRes( prevState => prevState.append(<p>{e.target.value)}</p>))
    }
  }
return(
    {Res}
)

If this us wrong, please tell me the correct way to solve similar problems please.

CodePudding user response:

Keeping JSX in state is an antipattern.

Instead of keeping the JSX in an array in state, keep the data in the array without JSX, then build the JSX when you are ready to render:

const YourComponent = () => {
  const [res, setRes] = useState([]);

  const test = (e) => {
    const {value} = e.target;

    if (e.code === "Enter") {
      setRes(prev => [...prev, value]);
    }
  };

  return (
    <div>
      {res.map(e => <p>{e}</p>)}
    </div>
  );
};

<p> is using index as key, which is a problem. How to fix it is application-specific depending on where your data is coming from and whether it can be removed from the array, whether it's unique, etc, but ideally generate an id.

Also, e.target.value shouldn't be accessed in a state setter callback. It's async so the event object might have gone stale by the time it's read. Pull out the primitive value into the handler closure.

I suggest picking better names: test and res are pretty meaningless.

Finally, instead of e.keyCode === 13, use e.code === "Enter".

  • Related