I am trying to change the input value on dynamically added input fields.
Each input field value is set to a state value which is made of an array.
Seems like there should be a simple solution for this.. But I can't just figure it out.
JSfiddle:
https://jsfiddle.net/o51Lkvm6/1/
handleInputChange = (e) => {
this.setState({
[e.target.name]: e.target.value
});
}
render() {
return (
<div>
{ this.state.data.map((d, index) =>
<input name={d.Name} type="text" className="form-control"
value={d.Name} onChange={this.handleInputChange} />
)}
</div>
);
}
Update:
Is it possible to solve this without having to use defaultvalue? Since React does not recommend "Uncontrolled Components"?
First of all there are couple issues with your code:
You forgot to bind your handler method or use arrow function to
preserve this context of a class. To fix that you can either put this
in Test constructor:
this.handleInputChange = this.handleInputChange.bind(this)
or modify your existing function to:
handleInputChange = e => {};
Input value should actually use the value which
corresponds to current item from state, like that:
value={this.state.data[index]["Name"]}
Later to access proper item in your stateData you have to somehow
store that index in the input. I did this by assigning it to
data-index attribute. Also you forgot to include key prop:
<input
key={d.ID}
data-index={index}
name={d.Name}
type="text"
className="form-control"
value={this.state.data[index]["Name"]}
onChange={this.handleInputChange}
/>
In your actual handleInputChange you were not targeting the correct
thing. You need to first get the appropriate item from the array and
then modify the name. I did it by copying the actual state and later
assigning it:
handleInputChange = e => {
const stateDataCopy = this.state.data.slice();
const objectCopy = Object.assign({}, stateDataCopy[e.target.dataset.index]);
objectCopy["Name"] = e.target.value;
stateDataCopy[e.target.dataset.index] = objectCopy;
this.setState({ data: stateDataCopy });
};
Here you can find working example:
ok I fixed it for you
do these 2 things
handleInputChange(e){ make this an arrow function so it has the concept of this like so: handleInputChange = (e) => {
and use defaultValue instead of value in the input
updated fiddle for you: https://jsfiddle.net/a17gywvp/1/
Related
export default function Form() {
const [user, setUser] = useState({
name: "",
numOfQs: 0
})
console.log(user)
function handleUserDataChange(event) {
setUser(prevUser => {
return {
...prevUser,
[event.target.name]: event.target.value
}
})
}
return (
<>
<input
type="text"
placeholder="username"
name="name"
value={user.name}
onChange={handleUserDataChange} />
<input
type="number"
name="numOfQs"
value={user.numOfQs}
onChange={handleUserDataChange} />
</>
)}
I was trying to build my form using react, and when I tried to use input[type: number] on the form field it was giving me this error, don't know why. I was reading through react docs about forms, and everything from the checkbox, radio buttons, textarea was all working fine. but when I used an input element of the type number, I got the following error.
*!Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property target on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist(). See fb.me/react-event-pooling for more information.
so, the problem only arises when an input of type "number" is introduced. when I remove it all of my other form elements work fine.
I'm still in the learning phase of react. please help me out.
This happened because the event that passed into the function is used as an asynchronous event.
To fix this, decompose the event object
function handleUserDataChange(event) {
const { name, value } = event.target;
setUser(prevUser => {
return {
...prevUser,
[name]: value
}
})
}
I have a warning that says
Warning: You provided a `value` prop to a form field without an `onChange` handler.
This will render a read-only field. If the field should be mutable use `defaultValue`.
`Otherwise, set either `onChange` or `readOnly`.`
Of course, I have googled a solution for it. One way to fix it is to replace "value" attribute with "defaultValues". But, this is causing another issue because my component is a controlled.
I could add onchange attribute and method to the fields. But the problem is that it will cause redundancy as I have a single onChange method on the tag that manages all the values and states. For example,
const [allStates, setAllStates] = useState({value_one: "", value_two:""});
function handleOnChange(event){
.........
//update the allStates state here
}
<Form onChange={handleOnChange}>
<input value={allStates.value_one} />
<input value={allStates.value_two} />
</Form>
What are the alternatives I have? Should I just ignore it since I can only see it on dev environments, the end users cannot and won't see it on the prod environment anyway?
It is a Helpful Warning by React, you can probably refer to this thread which discusses this.
https://github.com/facebook/react/issues/1118
Although adding the defaultValue should work for you, since your state has the latest value for the inputs, and when your component would render for the first time as long as the defaultValue is assigned to your <input>, the fields would reflect your state.
const [state, setState] = useState({});
const handleChange = (ev) => {
setState(prev_state => {
return {
...prev_state,
[ev.target.name]: ev.target.value
}
})
}
<form onChange={handleChange}>
<input name={"foo"} defaultValue={state.foo}/>
<input name={"bar"} defaultValue={state.bar}/>
</form>
The warning it is giving you is that you have provided the input with a value argument, so when you go to type in the input, it won't work:
const [allStates, setAllStates] = useState({
value_one: 'I will be display in the input initially', // <-- This text will already be entered in the text input.
value_two: ''
});
<input value={allStates.value_one} />
But since you added the value prop, you need to give it an onChange, otherwise the value of the field will always be the same and you won't be able to change it.
Ofcourse you can add the onChange like this:
const [allStates, setAllStates] = useState({
value_one: '',
value_two: ''
});
const handleOnChange = (event) => {
setAllStates({
...allStates,
// Now you can target the name prop
[event.target.name]: event.target.value
});
}
return (
<>
{/* I will suggest adding a name prop also */}
<input name="value_one" value={allStates.value_one} onChange={handleOnChange} />
<input name="value_two" value={allStates.value_two} onChange={handleOnChange} />
</>
);
The name prop is really useful for these one function setups, as it allows you to target the state value straight from the name.
But remember that the name values should be the same as the values in the state.
In vanilla js if we want to add a listener to a dom we can do like this
<div onclick="myFunction(this)">...</div>
but wen i do it inside react component this is refers to component class itself. how to handle something like this?
You should pass event in your function, and then you access DOM element with e.target.
For example if you want to handle input change, you can do something like this:
const [values, setValues] = useState({
username: '',
});
const handleChange = event => {
event.persist();
setValues(values => ({
...values,
[event.target.id]: event.target.value
}));
};
event.target.id is the id of DOM element and event.target.value is the value of the same element, which in this case is input.
<input
id="username"
type="text"
placeholder="Enter username"
onChange={handleChange}
value={values.username}
required
></input>
Also
Note:
If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.
In react u should use onClick (with capital C) and pass the event to your function
<div onClick={(e) => {myfunction(e)}}>...</div>
Then in your function, use event.target to get the clicked tag.
const myfunction = (event) => {
let id = event.target.id;
}
In your context, this refers to the DOM target element, so you'd define your function as:
function myFunction(target) { /* Code here */ }
But in react, when you define an input:
<input onClick={myFunction} />
Your function is given an event not a target, so your function is defined as:
function myFunction(event) { console.log(event.target) }
I want to use the same onChange handler for a series of inputs.
<input onChange={this.handleInputChange}
type="text"
data-input-name="name"
value={this.state.name}/>
so I am attempting to use this html data attribute to store the input's name. When I go to pull the attribute off in JavaScript, I am unable to access it.
handleInputChange = (event) => {
this.setState([event.target.inputName]: event.target.value})
}
I've tried a few permutations to no avail, and it seems difficult to debug since when I log the event.target I just see an html element in the JavaScript console.
Any advice on how to better debug this or where my syntax is going wrong?
I've noticed that you have missed an opening curly brace in your setState call. And that will throw a syntax error when you run it. It should be fixed like this:
handleInputChange = (event) => {
this.setState({[event.target.inputName]: event.target.value})
}
For accessing your data attribute from the handleInputChange, you can do it like this:
handleInputChange = event => {
this.setState({
[event.target.getAttribute('data-input-name')]: event.target.value,
});
};
And also, you can use the default name attributes that comes with these inputs like this:
handleInputChange = event => {
this.setState({
[event.target.name]: event.target.value,
});
};
// in your render fucntion
<input
onChange={this.handleInputChange}
type="text"
name="name"
value={this.state.name}
/>
This will work as the same as using data attributes. Hope this help!
You could pass the input name as an argument instead of having it as a property, like so:
<input onChange={(e) => this.handleInputChange(e,"someValue")}
type="text"
value={this.state.name}/>
and then
handleInputChange = (event, name) => {
this.setState([name]: event.target.value})
}
I was also able to find a somewhat dirty solution to pulling the value off of the event object.
event.target.attributes['data-input-name'].value
<input
defaultValue={this.props.str.name}
ref={(input) => { this.state.name = input; }}
name="name"
type="text"
className="form-control"
onChange={this.handleInputChange}
/>
handleInputChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
if(this.state.name.value === "") {
this.msg.show('Required fields can not be empty', {
time: 2000,
type: 'info',
icon: <img src="img/avatars/info.png" role="presentation"/>
});
}
I'm trying to set the default value like that and wanted to access it as well. I did like this and accessed the value with this.state.name.value but the thing is its working but showing the warning as
Do not mutate state directly, Use setState()
react/no-direct-mutation-state .
Getting "Do not mutate state directly, Use setState()", Why?
Because, you are mutating the state value inside ref callback method to store the node ref, Here:
this.state.name = input;
Solution:
Don't use state variable to store the reference, You can directly store
them in component instance because that will not change with time.
As per DOC:
The state contains data specific to this component that may change
over time. The state is user-defined, and it should be a plain
JavaScript object.
If you don’t use it in render(), it shouldn’t be in the state. For
example, you can put timer IDs directly on the instance.
Since you are using controlled input element, ref is not required. Directly use this.state.name with input element value property and this.state.name to access the value.
Use this:
<input
value={this.state.name || ''}
name="name"
type="text"
className="form-control"
onChange={this.handleInputChange}
/>
If you wanted to use ref then store the ref directly on instance, remove value property and you can remove the onChange event also, Use it like this:
<input
ref={el => this.el = el}
defaultValue={this.props.str.name}
name="name"
type="text"
className="form-control"
/>
Now use this ref to access the value like this:
this.el.value
you can instead clone the entire property value inside the with spread operator and then reform or edit the value for example :
state = {Counters: [{id:1,value:1},{id: 2,value: 2},{id: 3,value: 3},{id: 4,value: 4}]}
increment = (Counter) => {
//This is where the state property value is cloned
const Counters = [...this.state.Counters];
console.log(Counters);
const index = Counters.indexOf(Counter)
Counters[index].value++
this.setState({
Counters: this.state.Counters
})
}
Change your line number 3 as
ref={(input) => { this.setState({name: input}); }}