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>
</>
}
CodePudding user response:
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.
CodePudding user response:
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>
</>
);
};
CodePudding user response:
Instead for setting your state as html element try to set is as an empty string and show your input using ternary operator only if the state is not an empty string, Like :
import { useState } from "react"
export default()=>{
const [input,setinput]=useState("")
const AddInput=(name)=>{
setinput(name)
}
return (<>
{input ? <input type="text" value={input} /> : <></> }
<button onClick={()=>{AddInput('name1')}}>Add input with Name1</button>
<button onClick={()=>{AddInput('name2')}}>Add input with Name2</button>
</>)
}
Instead of using {input ? <input type="text" value={input} /> : <></> }
you can use {input && <input type="text" value={input} /> }