Search code examples
javascriptreactjstabular

How do you render or not render table data based on conditions, using a loop in React JS?


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!


Solution

  • 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.