I'm new to react and struggling to get this to work. I can display a mapped array, but I am trying to update the array, map it, then display it. Can't figure out how to get the mapped array to display after it's updated?
Tried to add the mappedItems to my function also, but that didn't seem to solve it. TIA.
import React, { Component } from 'react';
const itemsList = ['item1','item2'];
class RecieveInput extends React.Component {
constructor(){
super();
this.state = {
list: itemsList
}
}
render(){
const pressedEnter = event => {
if (event.key === 'Enter') {
this.state.list.push(event.target.value);
console.log(this.state.list);
}
}
const mappedItemsList = this.state.list.map( (listItem, i) => <li>{this.state.list[i]}</li> )
return(
<div>
<input
type ="text"
id="textInput"
placeholder="Enter Item Here"
onKeyPress={pressedEnter}
/>
<ol className='ol'>{mappedItemsList}</ol>
</div>
)
}
}
export default RecieveInput
this.state.list.push(event.target.value);. This should be done using the providedthis.setStatei.e.this.setState({ list: [...list, event.target.value ]});. React usesthis.setStateto know when state has been updated and theshouldComponentUpdatemethod of a class component only does a shallow comparison on references so if you do not create a new array when setting the state React will not see it as a change.