Sayed Murad
Sayed Murad

Reputation: 51

Browser Not showing Input Value when changing it

I have an example of how the value of the Input element will change but the browser won't show the current value, you can check in the DevTools of the browser that the value is changed.

I'm wondering why it's not showing the actual value of the Input element.

import { useState } from "react"


export default()=>{
const [input,setinput]=useState(<></>)

const AddInput=(name)=>{
  setinput(<input type='text' defaultValue={name} />)
}
return <>
{input}
<button onClick={()=>{AddInput('name1')}}>Add input with Name1</button>
<button onClick={()=>{AddInput('name2')}}>Add input with Name2</button>
</>
}

Upvotes: 1

Views: 61

Answers (2)

Chetan Kondawle
Chetan Kondawle

Reputation: 338

You are actually setting its default value and not the actual value thats why it is not getting updated

Make this change

setinput(<input type="text" value={name} />);

Entire code

import { useState } from "react";

export default () => {
  const [input, setinput] = useState(<></>);

  const AddInput = (name) => {
    setinput(<input type="text" value={name} />);
  };
  return (
    <>
      {input}
      <button
        onClick={() => {
          AddInput("name1");
        }}
      >
        Add input with Name1
      </button>
      <button
        onClick={() => {
          AddInput("name2");
        }}
      >
        Add input with Name2
      </button>
    </>
  );
};

Upvotes: 1

RubenSmn
RubenSmn

Reputation: 4662

Your input is not a controlled input. It only has a defaultValue which is the reason it shows value prop. If you remove the defaultValue from the input you will see that there is no value at all on the input.

To see the value prop change you need a controlled input, you can do this like so

const [inputValue, setInputValue] = useState("Your default value");

const AddInput=(name)=>{
  setinput(<input type='text' value={inputValue} onChange={(e) => setInputValue(e.target.value)} />)
}

The React docs have great documentation on how controlled inputs work.

Upvotes: 1

Related Questions