Reputation: 1095
I'm doing an exercise using React.js and am having trouble iterating through a data array and selectively rendering elements based on the properties in each data node.
The dataset is formatted like this:
var requests = [
{"id":1, "title":"request","updated":"2015-08-15","created":"2015-08-12","status":"Denied"}, ...]
My rendering code is looking for a flag value to determine what it should or should not be rendering. The logic is working fine (i.e. returning true or false when it should, a la console.log), but the rendering code, written in JSX, is giving me trouble. This is what I have so far in the tbody section:
<tbody>
{requests.map(function(row, i) {
{filter === requests[i].status || filter === "" ?
<tr key={i}>
<td style={tdStyle}>{row.title}</td>
<td style={tdStyle}>{row.status}</td>
<td style={tdStyle}>{row.created_at}</td>
<td style={tdStyle}>{row.updated_at}</td>
<td style={tdStyle}><a href="">delete</a></td>
</tr>
: null}
})}
</tbody>
I have looked at this link for guidance, but it doesn't seem to be working.
Any help would be greatly appreciated!
Upvotes: 1
Views: 2470
Reputation: 2032
As I mentioned in my comment, you need to return the computed value, this allows the map()
function to work properly.
Also, in this situation I would use the filter()
function to only map through the elements that meet your condition.
<tbody>
// use the filter function to get only the matching elements before mapping
{requests.filter(function(row){
// return true to include array element, false to exclude
return (filter === row.status || filter === "");
}).map(function(row, i) {
// always wrap jsx in parentheses because of line breaks in javascript syntax
// make sure to return, this actually adds it
return (
<tr key={i}>
<td style={tdStyle}>{row.title}</td>
<td style={tdStyle}>{row.status}</td>
<td style={tdStyle}>{row.created_at}</td>
<td style={tdStyle}>{row.updated_at}</td>
<td style={tdStyle}><a href="">delete</a></td>
</tr>
);
})}
</tbody>
Upvotes: 0
Reputation: 2503
const requests = [
{"id":1, "title":"Request from Nancy","updated_at":"2015-08-15 12:27:01 -0600","created_at":"2015-08-12 08:27:01 -0600","status":"Denied"},
{"id":2, "title":"Request from David","updated_at":"2015-07-22 11:27:01 -0600","created_at":"2015-07-15 12:27:01 -0600","status":"Approved"}
];
const jsx = function(filter) {
const isCorrectStatus = (x) => x.status === filter;
return <tbody>
{requests.filter(isCorrectStatus).map(function(row, i) {
return <tr key={i}>
<td>{row.title}</td>
<td>{row.status}</td>
<td>{row.created_at}</td>
<td>{row.updated_at}</td>
<td><a href="">delete</a></td>
</tr>
})}
</tbody>
}
const filter = 'Denied';
ReactDOM.render(jsx(filter), document.getElementById('app'));
I'd rewrite it as follows, we have a prebuilt filter method, we may as well use it rather than reimplementing the wheel, and it keeps our code a little cleaner.
Upvotes: 2