0

Following is my component definition.

I am receiving an input as Mistake Name and want to store it in array and display it.

import React, {Component} from 'react';


class AddMistake extends Component {

    constructor(props){
        super(props);
        this.state = {
            mistake: [],
            value: ''
        }
        this.handleChange = this.handleChange.bind(this);
        this.addMistake = this.addMistake.bind(this);
    }
    handleChange(event) {
        this.setState({value: event.target.value});
    }

    addMistake(event){
        this.setState({mistake: [].push(this.state.value)});
        console.log("Mistake is "+ this.state.mistake.length + " And Value is "+ this.state.value);
    }

    render(){
        return(
            <div>
                <input value={this.state.value} type='text' onChange={this.handleChange} /> 
                <button onClick={this.addMistake}> Add Mistake </button>
                <div>
                {this.state.mistake}
                </div>
                <div>{this.state.value}</div>

            </div>
        );
    }
} 

export default AddMistake;

Can someone recommend better way to handle this?

2 Answers 2

2
addMistake(event){
   this.setState((prevstate) => ({mistake: prevstate.mistake.concat([this.state.value]))
}); 
   console.log("Mistake is "+ this.state.mistake.length + " And Value is "+ this.state.value);
}

In render method

 render(){
  return(
    <div>
     <input value={this.state.value} type='text' onChange={this.handleChange} /> 
     <button onClick={this.addMistake}> Add Mistake </button>
      <div>
       {this.state.mistake.length && this.state.mistake.map(item =><p> {item} </p>) }
      </div>
       <div>{this.state.value}</div>
     </div>
        );
    }

this.state.mistake.length checks if we have anything in the array.

Sign up to request clarification or add additional context in comments.

9 Comments

A suggestion: array.concat is a much easier way to update state
mistake.concat(this.state.value) ?
mistake.concat([this.state.value]); otherwise you'd end up adding each character of the string individually
I see what you mean this.setState({mistake: this.state.mistake.concat([this.state.value]) })
specifically, this.setState({mistake: this.state.mistake.concat([this.state.value])})
|
0

Following syntax worked for me! Thank you @omar and @Hamms

addMistake(event){
    this.setState({mistake: this.state.mistake.concat([this.state.value])
 }); 
    console.log("Mistake is "+ this.state.mistake.length + " And Value is "+ this.state.value);
 }

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.