Reputation: 369
I am making an update form for user but I can't type in input tag when I added handleChange
Here is my code base:
const handleChange = (event) => {
const { name, value } = event.target;
// Update state
updatePlayersData((prevState) => ({
...prevState,
[name]: value,
}));
};
<input
value={title}
onChange={handleChange}
placeholder={title}
pattern="^[a-zA-Z0-9 ]+"
minLength="1"
maxLength="20"
/>
Upvotes: 0
Views: 789
Reputation: 636
Because you're setting your inputs value to title
variable everytime and not updating your title value.
<input
value={title} // you are not updating title value and using it on your value
onChange={handleChange}
placeholder={title}
pattern="^[a-zA-Z0-9 ]+"
minLength="1"
maxLength="20"
/>
as I understand it, you want to specify a default value. Try this one:
<input
defaultValue={title} // now it will change when you update input string
onChange={handleChange}
placeholder={title}
pattern="^[a-zA-Z0-9 ]+"
minLength="1"
maxLength="20"
/>
Upvotes: 1
Reputation: 6009
In your code input
doesn't have any name
attribute. But in onChange
method the state is being updated based on the name
of the input. Hence, the changes are not getting reflected in the input.
So by adding name="title"
attribute to the input
and providing value={data.title}
should work. Below I have added a snippet for the same
const { useState } = React;
const App = () => {
const [data, setData] = useState({});
const handleChange = (event) => {
const { name, value } = event.target;
setData((prevState) => ({
...prevState,
[name]: value,
}));
};
return <input
value={data.title}
onChange={handleChange}
placeholder={data.title}
pattern="^[a-zA-Z0-9 ]+"
minLength="1"
maxLength="20"
name="title"
/>
}
ReactDOM.render(<App />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Note: I have replaced updatePlayersData
with setData
for the example purpose. Also, in your code as per your requirement you can add any name
for the input. But then make sure the same prop in the data to be passed as value to the input.
Upvotes: 0
Reputation: 453
Kindly provide name="name_of_field"
property to input element.
It will assign the input to the specified name_of_field
and you can, later on, use it as input.name_of_field
Upvotes: 0