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. Here we will create dynamic lists in React.
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')
);
Recommendation
Create Popup Component in React
How to create charts in ReactJS
Create Drag and Drop List in React
MultiSelect Components in React
For more React Tutorials Click here, Node.js Tutorials Click here.
If you like this, share this.