Search code examples
reactjsinputstatetsx

TSX Input Value


I am developing a web app using React.JS.

I would like the input to be a default value, but the input can't be uneditable.

I have tried :

let [inputValue, setInputValue] = useState<string>('Value of Input')
return (
    <div className = "App">
        <input value={inputValue}></input>
    </div>

The problem with this is that i can't edit the input.


Solution

  • I think you need onChange on that input, and you can change state with that onChange event

    const handleOnChange = (event) => {
        setInputValue(event.target.value);
      };
    

    and you can add h1 to see what's inside the state

    <h1>this is what inputValue state content: {inputValue}</h1>
    

    and the whole code will look like this

    import { useState } from "react";
    
    export default function App() {
      const [inputValue, setInputValue] = useState("Value of Input");
    
      const handleOnChange = (event) => {
        setInputValue(event.target.value);
      };
      return (
        <div className="App">
          <h1>this is the content of inputValue state: {inputValue}</h1>
          <input onChange={(event) => handleOnChange(event)}></input>
        </div>
      );
    }