userden
userden

Reputation: 1683

Trying to make a simple ToDo list with React, how can I push an item to an array?

I'm trying to make a simple ToDo list with React. How can I push an item to an array? I'm trying to use ES6. I would like to click the button, and get the contents of the input field displayed in a list.

import React, { Component } from 'react';

class Example extends Component {
    constructor(props) {
        super(props);
        this.state = {
            query: [],
            item: ''
        }
    }

    render() {
        return(
            <div>
              <form>
                <fieldset>
                    <legend>Example</legend>
                    <input 
                      type="text"
                      onChange={e => {this.setState({item: e.target.value})}} />
                    <button 
                      onClick={() => {this.setState({ query: [...this.state.query, this.state.item]})}}>Add Item to Array
                    </button>
                </fieldset>
              </form>
            {
                this.state.query.map((q, key) => {
                    return(
                        <li key={key}>{q}</li>
                    )
                })
            }
            </div>
        )
    }
}

export default Example;

EDIT:

In the console, I see that an item is added to the array, however then the page refreshes, and the array is empty again. Should I add event.preventDefault somewhere to the button?

EDIT:

Solved it by adding type="button" to button. Instead of using the default 'submit' type. Now it doesn't refresh the page, and I can see items added to the array, and displayed as a list. I was just practising, so I know to store the data I would need a database etc. :)

Upvotes: 0

Views: 964

Answers (1)

userden
userden

Reputation: 1683

Solved it by adding type="button" to button. Instead of using the default 'submit' type. Now it doesn't refresh the page, and I can see items added to the array, and displayed as a list. I was just practising, so I know to store the data I would need a database etc. :)

Upvotes: 1

Related Questions