0

I'm a bit new to React, and with all new programming endeavors I am building a todo app. Everything seems to be working correctly except for one issue: When I enter a todo into the input field and click "submit", the todo is pushed into my array, however it doesn't immediately display. It is only when I change the text inside the input that the todo is displayed. I'm guessing this has something to do with the rendering happening on the handleChange function and not the handleSubmit function. Any help would be greatly appreciated.

Here is my AddTodo component

import React, { Component } from 'react';
import App from "./App"
import List from "./List"


class AddTodo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: '',
      array: []
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
     this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    event.preventDefault();
    var array = this.state.array
    array.push(this.state.value);
    console.log(array)
  }

  render() {
    return (
      <div>
        <form>
          <label>
            Name:
            <input type="text" value={this.state.value} onChange={this.handleChange} />
          </label>
          <input onClick={this.handleSubmit} type="submit" value="Submit" />
       </form>
       <List array={this.state.array}/>
       </div>
     );
   }
 }

And my List component

import React, { Component } from 'react';

class List extends Component{
  render(){
    return(
      <div>
      {
        this.props.array.map(function(item, index){
          return <li key={index}>{item}</li>
        })
      }
      </div>
    )
  }
}

export default List;
Ian Springer
  • 223
  • 2
  • 7
  • 19

2 Answers2

0

By default, invoking setState() calls the render() function. More info here: ReactJS - Does render get called any time "setState" is called?

Community
  • 1
  • 1
Doug
  • 1,435
  • 1
  • 12
  • 26
0

React renders an individual component whenever its props or state change. In order to make a change in the state, with a class component it's mandatory to use the this.setState() method, which among other things makes sure to call the render() when it's necessary.

Your handleSubmit() method is changing the array directly, which is forbidden (it's only allowed in the constructor in order to set the initial state)

If you use setState() it should work.

xabitrigo
  • 1,341
  • 11
  • 24