Just started with ReactJS and I'm looking for the most efficient code to display the array below in a table structure as described in the 'render' section. I have been using .map to iterate through the users/buttons objects, but with no success yet.
In my code sample below, I want to take the userData array and display the content in separate rows (html table format)ie.
Joe,Smith,[Click 1A],[Click2B] //'Click XX' are buttons
Mary,Murphy,[Click 2A],[Click2B]
How can I achieve this?
Thanks
var MyButton = require('./mybutton.js');
var userData =[{
userButtons: [
[{user: [{ id: 1, lastName: 'Smith', firstName: 'Joe',
buttons: [
{button:[{ id:0, value: "Click 1A" enabled:1}]},
{button:[{ id:1, value: "Click 1B" enabled:1}]}
]
}]}],
[{user: [{ id: 1, lastName: 'Murphy', firstName: 'Mary',
buttons: [
{button:[{ id:0, value: "Click 2A" enabled:1}]},
{button:[{ id:1, value: "Click 2B" enabled:1}]}
]
}]
}]
]}];
var DisplayData = React.createClass({
render: function() {
// render userButtons in a table with data using <MyButton> ie.
// <table>
// <tr><td>Joe</td><td>Smith</td><td>[Click 1A]</td><td>[Click 2A]</td</tr>
// <tr><td>Mary</td><td>Murphy</td><td>[Click 2B]</td><td>[Click 2B]</td></tr>
// </table>
}
}
});
React.render(
<DisplayData tArr = {userData} />
, document.getElementById('content')
);
// mybutton.js
var React = require('react');
module.exports = React.createClass({
render: function() {
return (
<button>{this.props.value}</button>
)
}
});
I would suggest you simplify your userData
if possible.. you have quite a bit of extra nested arrays that don't seem to be needed.
Something like this:
var userButtons = [
{
id: 1,
lastName: 'Smith',
firstName: 'Joe',
buttons: [
{
id: 0,
value: "Click 1A",
enabled: 1
}, {
id: 1,
value: "Click 1B",
enabled: 1
}
]
},
{
id: 2,
lastName: 'Murphy',
firstName: 'Mary',
buttons: [
{
id: 0,
value: "Click 2A",
enabled: 1
}, {
id: 1,
value: "Click 2B",
enabled: 1
}
]
}
];
Then it's easy to loop through and return the right elements:
return (
<table>
{
userButtons.map(function(ub) {
var buttons = ub.buttons.map(function(button) {
return (
<td>{button.value}</td>
)
});
return (
<tr>
<td>{ub.firstName}</td>
<td>{ub.lastName}</td>
{buttons}
</tr>
)
})
}
</table>
)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments