Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

usestate with object

import { useState } from 'react';
import './App.css';

function App() {
  const [details, setDetails] = useState({ email: "", password: "" })
  const onChange = (e) => {
    const { name, value } = e.target;
    setDetails({ ...details, [name]: value })
  }
  const submitHandler = (e) => {
    e.preventDefault();
    alert(JSON.stringify(details))
  }
  return (
    <div className="App">
      <form onSubmit={submitHandler}>
        email : <input type="text" name="email" onChange={onChange} value={details.email} />
       //or <input type="text" name="email" onChange={(e) => setDetails({ ...details, email: e.target.value })} value={details.email} /><br /><br />
          password :<input type="text" name="password" onChange={onChange} value={details.password} />
        <button type="submit">Submit</button>
      </form>
      <h2>{details.email}</h2>
      <h2>{details.password}</h2>
    </div>
  );
}

export default App;
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #usestate #object
ADD COMMENT
Topic
Name
9+1 =