#Preferred way to obtain values within a form on submit, React + TS

1 messages · Page 1 of 1 (latest)

shadow kraken
#

hey guys, I'm wondering what is the accepted way to obtain the values of the inputs within a form in React + TS, I got to this answer but I wonder if there are more elegant ways to do it:

import { FormEvent } from 'react'
import './App.css'

function App() {

  const onSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const usernameInput = (e.target as HTMLFormElement).elements.namedItem('username') as HTMLInputElement;
    const passwordInput = (e.target as HTMLFormElement).elements.namedItem('password') as HTMLInputElement;
    const password = passwordInput.value;
    const username = usernameInput.value;
    console.log('Username:', username);
    console.log('Password:', password);
  };

  return (
    <form onSubmit={onSubmit}>
      <label htmlFor="username">Username</label>
      <input name="username" type='text'/>
      <label htmlFor="password">Password</label>
      <input name="password" type='password'/>
      <button type='submit'>Next</button>
    </form>
  )
}

export default App

Thanks!

silent belfry
#

@shadow kraken Yeah, if you use e.currentTarget it's guaranteed to be the form element so you don't need to cast. (e.target can be a different element due to event propagation hence the weaker typings)

#

And the FormData API is simpler than working with elements.

#
const onSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const data = new FormData(e.currentTarget);
    const password = data.get("password");
    const username = data.get("username");
    console.log("Username:", username);
    console.log("Password:", password);
};
#

Though personally, I more commonly use individual state and 'controlled' inputs rather than uncontrolled inputs - it depends on what you're doing with it, really.