user3032373 user3032373 - 5 months ago 16
jQuery Question

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'
},{
'name': 'test3'
},{
'name': 'test4'
},{
'name': 'test5'
}];


And HTML structure should create like this -

<ul>
<li>
<div><span>{name}</span></div>
<div><span>{name}</span></div>
<div><span>{name}</span></div>
</li>
<li>
<div><span>{name}</span></div>
<div><span>{name}</span></div>
<div><span>{name}</span></div>
</li>
</ul>


I have created one global variable with the constant (
var abc = 3
) as value.
and using
_.map()
for iterating over element. Is there any other easier way to do this? I am using React and underscore.js on my project.

Answer

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) => (
            <ul key={i}>
                {_.map(innerItem, ({name}, j) => (<li key={j}>{name}</li>))}
            </ul>
        ))}
    </span>