Unable to get values in console! What am I doing it incorrectly?
Attached below is the functional component of React
The Handler Functions
import React, { useState, useRef } from 'react';
const SimpleInput = (props) => {
const nameInputRef = useRef();
const [enteredName, setEnteredName] = useState('');
const nameInputChangeHandler = (event) => {
setEnteredName(event.target.value);
};
const formSubmissionHandler = (event) => {
event.preventDefault();
console.log(enteredName);
const enteredName = nameInputRef.current.value;
console.log(enteredName);
};
The JSX Code
return (
<form>
<div className="form-control" onSubmit={formSubmissionHandler}>
<label htmlFor="name">Your Name</label>
<input
ref={nameInputRef}
type="text"
id="name"
onChange={nameInputChangeHandler}
/>
</div>
<div className="form-actions">
<button>Submit</button>
</div>
</form>
);
};
export default SimpleInput;
CodePudding user response:
formSubmissionHandler
should have on the form
element rather than the div
element.
return (
<form onSubmit={formSubmissionHandler}>
<div className="form-control">
<label htmlFor="name">Your Name</label>
<input
ref={nameInputRef}
type="text"
id="name"
onChange={nameInputChangeHandler}
/>
</div>
<div className="form-actions">
<button>Submit</button>
</div>
</form>
);