How To Create Html Structure Which Will Allow Only 3 Div Elements In Each Li. In React + Underscore.js
For creating this structure i want to use only underscore.js methods. I have below array . var xyz = [{ 'name': 'test' },{ 'name': 'test1' },{ 'name': 'test2
Solution 1:
An example of a pure React function (it could also be a component), you could do something like the following:
<span>
{_.map(_.chunk(xyz, 3), (innerItem, i) => (
<ulkey={i}>
{_.map(innerItem, ({name}, j) => (<likey={j}>{name}</li>))}
</ul>
))}
</span>
Solution 2:
Try this:
$(document).ready(function(){
var xyz = [{'name':'test'},{'name':'test1'},{'name':'test2'},{'name':'test3'},{'name':'test4'},{'name':'test5'}];
var htmlStr = "<ul><li>";
var cnt = 0;
$(xyz).each(function(i,v) {
if(cnt != 0 && cnt % 3 == 0) {
htmlStr += "</li><li>";
}
htmlStr += "<div><span>"+v.name+"</span></div>";
cnt++;
});
htmlStr += "</li></ul>";
$("#test").html(htmlStr)
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><divid="test"></div>
Solution 3:
You can split the array into chunks and use underscore _.template method for creating html:
var xyz = [{
'name': 'test'
},{
'name': 'test1'
},{
'name': 'test2'
},{
'name': 'test3'
},{
'name': 'test4'
},{
'name': 'test5'
}];
var chunkedXyz = _.chain(xyz).groupBy(function(element, index){
returnMath.floor(index/3);
}).toArray().value();
var liTemplate = _.template("<% _.each(liElements, function(liContent) { %> <div><span><%= liContent.name %></span></div> <% }); %>");
var ulTemplate = _.template("<% _.each(chunkedXyz, function(liItem) { %> <li><%= liTemplate({liElements: liItem}) %></li> <% }); %>");
var layout = "<ul>" + ulTemplate({
chunkedXyz: chunkedXyz,
liTemplate: liTemplate
}) + "</ul>";
console.log(layout.toString());
Post a Comment for "How To Create Html Structure Which Will Allow Only 3 Div Elements In Each Li. In React + Underscore.js"