skip to Main Content

Here is my code:

import { useState } from "react";

const Testing = () => {
    const [testa, setTesta] = useState({ Nickname: "Testing" });
    
    return (
        <>
            <button type="button" onClick={(e) => setTesta({})}>Add</button>
            <input type="text" value={testa?.Nickname} onChange={e => setTesta({ Nickname: e.target.value })} />
            <p>Output: {testa?.Nickname}</p>
        </>
    );
};
export default Testing;

When the page initially loads the textbox value and the text below it both reflect the correct Nickname value.

screenshot of initial load

When I type into the textbox the Nickname is correctly updated in both places.

updated text

When I click the Add button to reassign the state to an empty object, the output correctly disappears, but the textbox value remains unchanged.

unchanged textbox value

What causes the difference between the input value and the plain text in this case?

2

Answers


  1. The issue is with your button’s onClick event. You’re setting the state testa to an empty object with no Nickname key. Try this instead:

    onClick={e => setTesta({ Nickname: "" })}
    

    Also, not sure why you had to set it as an object. I would have set it to a string.

    Login or Signup to reply.
  2. The issue with your code is that when setTesta({}) is called, testa becomes an empty object, and testa?.Nickname becomes undefined. React throws an error because the value prop of the element expects a string or undefined, but when value={undefined}, the input’s displayed value doesn’t update as expected. The right code would be:

    <input type="text"
        value={testa?.Nickname || ""} // Provide a fallback value
        onChange={e => setTesta({ Nickname: e.target.value })}
    />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search