Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
Why can't I append a child using useState in React?

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.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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".

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!