aaayumi
aaayumi

Reputation: 1274

How can I pass array to object in the state in React.js

I'm making a list using React.js. This application will contains two lists and a user can create a list with some items.

For instance,

1) A list of lists (eg 1) Fruit list 2) Vegetable list)

2) A list of items( eg 1) Fruit -- 1 Apple, [2] Banana, [3] Orange )

enter image description here

The data of list is stored as array and list of items is stored array in object. What I cannot figure it out is to pass array to object in the state.

Here is my code: App.js

class App extends Component {

 constructor() {
 super();
 this.state = {
 lists: [], // this holds the name of each list
 items: {} // this property names of this object are the names of the lists; their values are arrays of the items in each list
 };
}

handleAddList(list) {
   let lists = this.state.lists;
   lists.push(list);
   let item = [lists] // how can I pass array to object?? 
   this.setState({
       lists: lists,
       items: item
   })
  console.log(this.state)
}

handleAddItem(item) {
    let items = this.state.items;
    items.push(item);
    this.setState({
       items
    })
 }
render() {
   return (
    <div className="App">

     <AddList addList={this.handleAddList.bind(this)} />
     <div id="listsDiv" className="List">
        <Lists lists={this.state.lists} items={this.state.items} addItem={this.handleAddItem.bind(this)} />
     </div>
     </div>
    );
   }

 }

AddList.js

class AddList extends Component {

 constructor(){
     super();
     this.state = {
        newList : {}
     }
 }

handleSubmit(e) {
     e.preventDefault(); // this prevents the page from reloading -- do not delete this line!

    if(this.refs.id.value ===''){
        alert('Add list')
    } else {
        this.setState({
            lists: this.refs.id.value
        }, function(){
        this.props.addList(this.state.lists);
   });
   }
 }

render() {
return (
  <div id="addListDiv">
  <form onSubmit={this.handleSubmit.bind(this)}>
  <div id='addList'>
  <label>What will be on your next list?&nbsp;
  <input type='text' ref='id' id='newID'></input>
  </label>
  </div><br />
  <input type='submit' value='Create List' />
  </form>
  </div>
);
}
}

Upvotes: 3

Views: 6816

Answers (1)

Hemerson Carlin
Hemerson Carlin

Reputation: 7424

If this is a list, you should initialize it as an empty array []. Also, if this is a list of list (as you say), maybe keep them in only one state prop where each key maps to a specific list type.

this.state = {
  lists: {
    fruits: ['apple', 'banana', 'orange'],
    vegetables: ['tomato', 'carrot', ...],
  }
}

So every time you add a new item to any of the lists, state manipulation gets easier:

addItem(type, item) {
  this.setState({
    lists: {
      ...this.state.lists,
      [type]: [
        ...this.state.lists[type],
        item,
      ]
    }
  })
}

Upvotes: 1

Related Questions