import React, { useState } from "react";
import axios from "axios";
const SignUp = () => {
const [user, setUser] = useState({
name: "",
email: "",
password: ""
});
const handleChange = (e) => {
const { name, value } = e.target;
setUser({
...user,
[name]: value
});
};
const register = () => {
const { name, email, password } = user;
if (name && email && password) {
axios
.post("http://localhost:8800/api/auth/signup", user)
.then((res) => console.log(res))
.catch((error) => console.log(error));
} else {
alert("Invalid input");
}
};
return (
<form>
<h1>Sign up</h1>
<br />
<span className="input"></span>
<input
type="text"
className="name"
value={user.name}
onChange={handleChange}
placeholder="Full name"
required
/>
<span className="input"></span>
<input
type="email"
className="email"
placeholder="Email address"
required
value={user.email}
onChange={handleChange}
/>
<span id="passwordMeter"></span>
<input
type="password"
className="password"
placeholder="Password"
value={user.password}
onChange={handleChange}
/>
<button type="submit" onClick={register}>
<span>Sign up</span>
</button>
</form>
);
};
export default SignUp;
I have already set up the backend server, running on localhost port 8800. It includes the user schema and POST method for user registration. However, the issue I’m currently facing is that I am unable to input any text within the input fields. The goal is to capture the user’s information and eventually store it in MongoDB.
3
Answers
Your input element’s
value
s are controlled by youruser
state, so if you don’t update your state correctly then you won’t be able to type inside your inputs. Your problem is that you’re trying to grab thename
attribute from your input element to determine which property in your state to update, however, your input elements don’t have aname
attribute so your state can’t update correctly and thus allow your inputs to work correctly.To fix this, set a
name
attribute on each of your inputs to the same value as name of the property you’re reading in thevalue
attribute:You have to simply add a
name
attribute, because you are targeting the element but it is not finding which element you are targeting.so the name attribute will help.