I'm trying to get data from 2 text boxes using react useState. But when I check the console.log
, it takes text letters one by one as an array.
create.js
import React, {useState} from 'react'
import { Form, Button, FormGroup, FormControl, ControlLabel } from "react-bootstrap";
export default function Create() {
const[firstName, setFirstName] = useState('');
const[lastName, setLasttName] = useState('');
console.log(firstName);
console.log(lastName);
return (
<div>
<div>create</div>
<div>
<Form>
<Form.Group className="mb-3" >
<Form.Label>First Name</Form.Label>
<Form.Control type="text" name='fName'
onChange={(e)=> setFirstName(e.target.value)}
placeholder="Enter first name" />
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Last Name</Form.Label>
<Form.Control type="text" name='lName'
onChange={(e)=> setLasttName(e.target.value)}
placeholder="Enter last name" />
</Form.Group>
<Button variant="primary" type="submit">
Submit
</Button>
</Form>
</div>
</div>
)
}
App.js
import './App.css';
import Create from './Components/create';
function App() {
return (
<div className="App">
<h2>Hello</h2>
<Create/>
</div>
);
}
export default App;
CodePudding user response:
The onChange
function gets triggered every time the input changes. If you want it to trigger only once, when you are done typing, you can use onBlur
this will assign the values only when the input field gets blurred.
Here's a sandbox for you to play with. Make sure you check the console to see when firstName gets updated https://codesandbox.io/s/pedantic-tharp-rfnxqg?file=/src/App.js
I would highly suggest that you check out React Hook Forms
CodePudding user response:
import React, {useState} from 'react'
import { Form, Button, FormGroup, FormControl, ControlLabel } from "react-bootstrap";
export default function Create() {
const[firstName, setFirstName] = useState('');
const[lastName, setLasttName] = useState('');
const submitForm =(e)=>{
console.log(firstName)
console.log(lastName)
e.preventDefault()
}
return (
<div>
<div>create</div>
<div>
<Form onSubmit={(e)=>submitForm(e)}>
<Form.Group className="mb-3" >
<Form.Label>First Name</Form.Label>
<Form.Control type="text" name='fName'
onChange={(e)=> setFirstName(e.target.value)}
placeholder="Enter first name" />
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Last Name</Form.Label>
<Form.Control type="text" name='lName'
onChange={(e)=> setLasttName(e.target.value)}
placeholder="Enter last name" />
</Form.Group>
<Button variant="primary" type="submit">
Submit
</Button>
</Form>
</div>
</div>
)
}