Matt Allen
Matt Allen

Reputation: 15

React: How to display mapped array after button press?

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

Upvotes: 1

Views: 120

Answers (1)

Drew Reese
Drew Reese

Reputation: 202605

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]
    }));
  }
}  

Upvotes: 3

Related Questions