Reputation: 821
I don't know what might be wrong here, but i am following a tutorial and writing the same lines of code, but it seems that i am getting an error when i add this block of code.
setTeacherLoginData({
...teacherLoginData,
[event.target.name]:event.target.value
});
i am thinking that my error is related to this.
Since the value attribute is not updating, it's not possible to edit the given input field. You can solve this by adding an onChange event and the value attribute to the input field
this is the code i have written so far
const [ teacherLoginData, setTeacherLoginData ] = useState({
email: '',
password: '',
});
const handleChange = (event) => {
setTeacherLoginData({
...teacherLoginData,
[event.target.name]:event.target.value
});
};
const submitForm = () => {
console.log(teacherLoginData);
};
return (
<input value="{teacherLoginData.email}" onChange="{handleChange}" type="text" className="form-control" />
<input value="{teacherLoginData.password}" onChange="{handleChange}" type="password" className="form-control" />
<button onClick="{submitForm}" className="btn btn-primary">Login</button>
)
Upvotes: 0
Views: 644
Reputation: 91
You are passing literal strings into the props of your html <input/>
and <button/>
.
This makes sense in vanilla HTML to set attributes of the <input/>
and <button/>
tags, but this is not what you want in React, which uses JSX
instead of HTML
syntax.
HTML Example:
<input value="{teacherLoginData.email}" onChange="{handleChange}" type="text" className="form-control" />
In React we write JSX which is something like JS + HTML.
Here we speak of props
instead of attributes
for a html element. You pass props similar to html, however you can pass javascript objects as well using the {}
braces.
JSX:
<input value={teacherLoginData.email} onChange={handleChange} type="text" className="form-control" />
Noticed I remove the ""
from the value
and onChange
prop to actually pass the functions instead of a string containing "teacherLoginData.email".
If you use quotes you are passing a string instead of the actual javascript reference of a function. For some props it's intended to pass a string i.e. the type
& className
prop of this <input/>
.
Here is a link to the docs of JSX to get you familiar with it: https://reactjs.org/docs/jsx-in-depth.html
Upvotes: 1
Reputation: 35847
In addition to the issues that peetzweg's answer mentions, you are missing name
attributes on your form inputs. This means that the event.target.name
in your handleChange
function will not be populated.
Upvotes: 1