A
A
Alexey Milyutin2019-05-23 00:44:34
JavaScript
Alexey Milyutin, 2019-05-23 00:44:34

How to draw an element using the data from the object?

Hello, I am writing a todo application, at first I implemented a simple todo list mechanism with writing text to an array. However, now I decided to expand the functionality and I want an array of objects.

this.state = {
todoList: [{
key: 0,
text: '',
done: false
}]
}

How to rewrite these lines so that they create an object in an array with the text from the input?
handleSubmit = (e) => {
    if (e.keyCode === 13 && e.target.value !== '') {
      console.log('success');
      const { value } = e.target;
      this.setState(prevState => ({
        todoValue: [...prevState.todoValue, value]
      }));
      e.target.value = '';
    }
  }

Here is the whole code:
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      todoValue: []
    };
  }
  render() {
    return (
      <div className="body-container">
        <h1>To Do List</h1>
        <input placeholder="Введите заметку" type="text" onKeyDown={this.handleSubmit}/>
        <input type="button" value="Очистить список" className="resetBtn" onClick={this.handleReset}/>
        <AlertSelect />
        <hr />
        <ul>
          {this.state.todoValue.map((text, index) => (
            <Li click={this.handleClick} key={index} text={text}/>
          ))}
        </ul>
      </div>
    )
  }

  handleReset = () => {
    this.setState({
      todoValue: []
    })
  }

  handleSubmit = (e) => {
    if (e.keyCode === 13 && e.target.value !== '') {
      console.log('success');
      const { value } = e.target;
      this.setState(prevState => ({
        todoValue: [...prevState.todoValue, value]
      }));
      e.target.value = '';
    }
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-05-23
@doppelgangerz

this.setState(state => ({
  todoList: [...state.todoList, { id: nanoid(8), text: value, done: false }],
}));

nanoid is used to generate id
{this.state.todoList.map(todo => (
  <Todo click={this.handleClick} key={todo.id} todo={todo} />
))}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question