I'm trying to use non state variable 'newItem' to hold the input value
import React, { Component } from 'react';
class List extends Component {
constructor() {
super();
this.state = { items: [1, 2] };
this.newItem = undefined;
}
changeNewItem = e => {
this.newItem = e.target.value;
console.log(this.newItem);
};
addItem = e => {
if (e.keyCode !== 13) return;
var tmp_list = this.state.items;
tmp_list.push(this.newItem);
this.setState({ items: tmp_list }, () => {
this.newItem = '';
});
};
render() {
return (
<div>
<ul>
{this.state.items.map(item => (
<li key={item}>{item}</li>
))}
</ul>
<input
type="text"
placeholder="add item"
value={this.newItem}
onChange={this.changeNewItem}
onKeyUp={this.addItem}
/>
</div>
);
}
}
export default List;
When I press enter key in textbox the item gets added to the array but getting error as below
index.js:1452 Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: in input (at List.js:29) in div (at List.js:23) in List (at App.js:9) in App (at src/index.js:8)