Set value to an input field in React (TypeScript)

How to set value to an input field in React (TypeScript)

Posted by Raquel Crist on July 12, 2022

Set value to an input field in React (TypeScript)

How to set value to an input field in React (TypeScript)

Posted by Raquel Crist on July 12, 2022

Here is how you set the value to an input field in React (TypeScript).

In a class component:

export default class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            location:"New York"
        };
    }

    handleChange = (e) =>{
        this.setState({location:e.target.value})
    }

    render() {

        return (
           <form>
              <input type="text" name="location" value={this.state.location || ""} onChange= 
              {(e)=>this.handleChange(e)} required/>
           </form>
        )
    }
}

In the class compnent above the a state is used to set the value within the input field.

In order to change the value when the user types, the onChange event sets the handleChange method.

In function component:

function App() {
  const [location, setLocation] = useState("New York");

  return (
      <form>
        <input type="text" name="location" value={location || ""} onChange={(e) => 
        setLocation(e.target.value)} required/>
      </form>
  );
}

export default App;

In the function component above the useState hook is used to set the value within the input field. 

In order to change the value when the user types, the onchange event is set just like in the class component.

The only difference is the setLocation function is placed directly in the event.

You can setState directly in the onChange event in class companent as well.