DEV Community

Cover image for Create dynamic lists in React
Chetan Rohilla
Chetan Rohilla

Posted on • Edited on • Originally published at w3courses.org

Create dynamic lists in React

Dynamic lists are the lists that automatically add or remove based on the conditions. They are easy to set up and they maintain themselves, which makes them a great choice for building lists around information that changes frequently.

Create dynamic lists in React

class App extends React.Component{

  state = {
    lists : {
      'list-1' : 'PHP',
      'list-2' : 'Wordpress'
    }
  }

    addList = (list) => {

      var timestamp = (new Date()).getTime();

      this.state.lists['list-' + timestamp ] = list;

      this.setState({ lists : this.state.lists });
     }

     removeList = (listKey) => {
      delete this.state.lists[listKey];
      this.setState({ lists : this.state.lists });
     }

     render() {
      return (
        <div className="component-wrapper">
          <ItemList lists={this.state.lists} removeList={this.removeList}/>
          <AddListForm addList={this.addList} />
        </div>
       );
      }

     }


     class ItemList extends React.Component{

      render () {
        return (
          <div className="container">
            <ul className="list-group text-center">
              {
                Object.keys(this.props.lists).map(function(key) {
                  return <li className="list-group-item list-group-item-info">{this.props.lists[key]} <span onClick={()=>this.props.removeList(key)}>X</span></li>
                }.bind(this))
              }
            </ul>
           </div>
          );
        }
      }



      class AddListForm extends React.Component{

        createList = (e) => {
          e.preventDefault();

          var list = this.refs.listName.value;

          if(list.length > 0) {
            this.props.addList(list);
          }

          this.refs.listForm.reset();
        }

        render = () => {
          return(
            <form className="form-inline" ref="listForm" onSubmit={this.createList}>
              <div className="form-group">
                <label for="listItem">
                  List Name
                  <input type="text" id="listItem" className="form-control" placeholder="e.x.lemmon" ref="listName" />
                </label>
              </div>
              <button type="submit" className="btn btn-primary">Add List</button>
            </form>
          )

        }
      }

      React.render(
        <App />,
        document.getElementById('app')
      );
Enter fullscreen mode Exit fullscreen mode

Please like share subscribe and give positive feedback to motivate me to write more for you.

For more tutorials please visit my website.

Thanks:)
Happy Coding:)

Top comments (0)