Using a script for filtering/sorting list in React Studio
List/Grid element has now a new script feature for manipulating the list data source array directly in the Studio’s UI.
Here is a live demo of an example project with list filtering implemented with a script. Download the example React Studio project file here.
How do I add the script?
Simply select List/Grid element from design canvas and click “”Edit script” button from the inspector panel on the right. Editor has variable named “items” which contains all items for list data. You can then e.g. filter the list based on Data slot value or arrange the list or even add or remove items from the list data source. When you’re ready click save and run the app in browser.
Example script for filtering list based on value in Data slot.
// This function filters items for the List / Grid element.
// There is a variable named ‘items’ that provides item values.let filteredItems = [];
let filterStr=this.props.appActions.dataSlots[‘ds_filter’]; // Data slot value
filterStr=filterStr.toLowerCase(); // Lowercase the filter string// Loop through all items and add item to new array if item includes filter string
items.forEach(item => {;
if (item[‘todo’].toLowerCase().includes(filterStr)) {
filteredItems.push(item);
}
});
items=filteredItems;
return items;
In this code we take value from Data slot (ds_filter) to variable and check if the list item’s “todo” property contains the filter string. If string is found then the item is added to new array which is returned in the end of the code snippet.
P.S. Scripts are handy for prototyping or manipulating list data in client side. When using a real backend you should consider doing the filtering in the API instead of downloading all rows and filtering in client side.
Download React Studio from www.reactstudio.com