1

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

enter image description here

1
  • 1
    You should not mutate the state directly this.state.list.push(event.target.value);. This should be done using the provided this.setState i.e. this.setState({ list: [...list, event.target.value ]});. React uses this.setState to know when state has been updated and the shouldComponentUpdate method 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. Commented Feb 7, 2021 at 22:23

1 Answer 1

3

Issue

The pressedEnter callback should be declared in the component, not the render function. It should also not mutate the state object by pushing into the state array.

Solution

Move the pressedEnter handler into the component and use this.setState to enqueue an update. You need to shallow copy the existing state and append the new element into it so your list state is a new array reference.

const pressedEnter = event => {
  const { value } = event.target;
  if (event.key === 'Enter') {
    this.setState(prevState => ({
      list: prevState.list.concat(value), // or [...prevState.list, value]
    }));
  }
}  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.