1

my app class component with it's state that get's updated when i press enter but doesn't immediately re-render the DOM


  constructor(props){
    super(props)
    
    this.state = {
      todoItemCurrent: '',
      todoList: []
    }

    this.handleChange = this.handleChange.bind(this)
    this.onSubmit = this.onSubmit.bind(this)
  }

  handleChange(e){
    this.setState({ todoItemCurrent: e.target.value }, ()=> {
      this.onSubmit(e)
    })    
  }

onSubmit(e){
  if(e.key === 'Enter'){
    this.state.todoList.push( { id: this.state.todoList.length + 1, todoItem: this.state.todoItemCurrent }  )
  }
  console.log( this.state)
  // console.log( this.state.todoList)
}

  render(){
    console.log(this.state.todoList)
    return (
      <div className="container">
        <header>
            <h1> TO-DO LIST APP</h1>
        </header>

   <TextBoxComponent value = { this.state.todoItemCurrent } placeholder = {`type here and hit enter to add an item`} handleChange = { this.handleChange } onEnter = {this.onSubmit} />

<ListComponentContainer todoList = { this.state.todoList } />
    </div>
    ); 
  }
}

export default App;

the text input component where i get the value from

const TextBoxComponent = ({ placeholder, handleChange, onEnter ,value })=> {
    return (
        <input className="text-box" type="text" value={ value } placeholder= { placeholder} onChange = { handleChange } onKeyDown = { onEnter } />
    );
}
export default TextBoxComponent

my list component, where i want to put the value in an li element and then append the li to the ul element

const ListComponentContainer = ( props ) => (   
    <ul> 
        { props.todoList.map( ({id, todoItem}) => (
            <li key={ id }> {todoItem} </li>
        )) }
    </ul>
);
export default ListComponentContainer
  • `this.state.todoList.push(` mutates state directly. You're not supposed to do that. –  Jun 02 '22 at 09:28

0 Answers0