I am working on Reactjs and using nextjs framework. Right now I have a form and want to get the input type text value am getting following error on my screen
TypeError: Cannot read property 'useState' of null
Here is my current code:
<form onSubmit="{check_login}">
<div className="form-group">
<label>Username or email *</label>
<input
type="text"
name="email"
className="form-control p_input"
onChange="{handleEmail}"
value="{state.email}"
/>
</div>
<div className="text-center">
<button
type="submit"
className="btn btn-primary btn-block enter-btn"
>Login</button>
</div>
</form>
And for get value I am using following code:
const [state, setState] = useState({ email: "", password: "" });
const handleEmail = (e: any) => {
const value = e.target.value;
setState({
...state,
[e.target.name]: value,
});
};
const check_login = (e: any) => {
e.preventDefault();
const email = state.email;
alert("email is " email);
};
How do I fix this error?
CodePudding user response:
Your code should work, just add import { useState } from "react";
CodePudding user response:
first you need add import { useState } from "react";
then your value="{state.email}"
is not correct, JSX use value={state.email}
, and the same for other parts
CodePudding user response:
I think you're doing it wrong. Don't make an object inside the useState()
instead, separate out the email and the password and make separate useState()
for them.
like :-
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
I have made a working example which might help you get a little bit more clarity on the topic. You can check out the CodeSandbox Here