• + 0 comments

    all testcases are passed

    App.jsx

    import "h8k-components";
    import Articles from "./components/Articles";
    import "./App.css";
    import { useState } from "react";
    
    function App({ articles = [] }) {
      const [orderBy, setOrderBy] = useState(null)
    
      const handleMostUpvoted = () => setOrderBy("upvotes")
      const handleMostRecent = () => setOrderBy("date")
      return (
        <>
          <h8k-navbar header="Sorting Articles"></h8k-navbar>
          <div className="App">
            <div className="layout-row align-items-center justify-content-center my-20 navigation">
              <label className="form-hint mb-0 text-uppercase font-weight-light">
                Sort By
              </label>
              <button
                data-testid="most-upvoted-link"
                className="small"
                onClick={handleMostUpvoted}
              >
                Most Upvoted
              </button>
              <button
                data-testid="most-recent-link"
                className="small"
                onClick={handleMostRecent}
              >
                Most Recent
              </button>
            </div>
            <Articles articles={articles} orderBy={orderBy} />
          </div>
        </>
      );
    }
    
    export default App;
    

    Article,jsx

    import React from "react";
    
    function Articles({ articles = [], orderBy }) {
      const sortArticle = (data) => {
        if (orderBy) {
          if (orderBy === "upvotes") {
            return data.sort((a, b) => b.upvotes - a.upvotes)
          } else if (orderBy === 'date') {
            return data.sort((a, b) => new Date(b.date) - new Date(a.date))
          }
        } else return data.sort((a, b) => b.upvotes - a.upvotes)
    
      }
      return (
        <div className="card w-50 mx-auto">
          <table>
            <thead>
              <tr>
                <th>Title</th>
                <th>Upvotes</th>
                <th>Date</th>
              </tr>
            </thead>
            <tbody>
              {sortArticle(articles)?.map((article, index) => (
                <tr data-testid="article" key={`article-${index}`}>
                  <td data-testid="article-title">{article.title}</td>
                  <td data-testid="article-upvotes">{article.upvotes}</td>
                  <td data-testid="article-date">{article.date}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    }
    
    export default Articles;