Skip to content

Frontend assignment #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
38 changes: 38 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"name": "assignment",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^13.0.0",
"@testing-library/user-event": "^13.2.1",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Binary file added public/favicon.ico
Binary file not shown.
43 changes: 43 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
Binary file added public/logo192.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/logo512.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 25 additions & 0 deletions public/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
3 changes: 3 additions & 0 deletions public/robots.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
Empty file added src/App.css
Empty file.
8 changes: 8 additions & 0 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import "./App.css";
import Table from "./components/Table";

function App() {
return <Table />;
}

export default App;
50 changes: 50 additions & 0 deletions src/__tests__/Pagination.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Pagination.test.js
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import Pagination from '../components/Pagination';

describe('Pagination Component', () => {
const setup = (props) => {
const defaultProps = {
currentPage: 2,
totalPages: 5,
onPageChange: jest.fn(),
...props,
};
render(<Pagination {...defaultProps} />);
return defaultProps;
};

test('renders pagination buttons correctly', () => {
setup();

const nav = screen.getByLabelText(/Pagination Navigation/i);
expect(nav).toBeInTheDocument();

const previousButton = screen.getByLabelText('Previous Page');
const nextButton = screen.getByLabelText('Next Page');
expect(previousButton).toBeInTheDocument();
expect(nextButton).toBeInTheDocument();

for (let i = 1; i <= 5; i++) {
const pageButton = screen.getByRole('button', { name: `Page ${i}` });
expect(pageButton).toBeInTheDocument();
}
});

test('calls onPageChange when a different page button is clicked', () => {
const { onPageChange, currentPage } = setup();

const nextButton = screen.getByLabelText('Next Page');
fireEvent.click(nextButton);
expect(onPageChange).toHaveBeenCalledWith(currentPage + 1);

const previousButton = screen.getByLabelText('Previous Page');
fireEvent.click(previousButton);
expect(onPageChange).toHaveBeenCalledWith(currentPage - 1);

const pageThreeButton = screen.getByRole('button', { name: 'Page 3' });
fireEvent.click(pageThreeButton);
expect(onPageChange).toHaveBeenCalledWith(3);
});
});
46 changes: 46 additions & 0 deletions src/__tests__/Table.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Table.test.js
import React from 'react';
import { render, screen } from '@testing-library/react';
import Table from '../components/Table';

const fakeData = [
{ "s.no": 1, "percentage.funded": 50, "amt.pledged": 1000 },
{ "s.no": 2, "percentage.funded": 75, "amt.pledged": 2000 },
];

describe('Table Component', () => {
beforeEach(() => {
jest.spyOn(global, 'fetch').mockResolvedValue({
ok: true,
json: async () => fakeData,
});
});

afterEach(() => {
global.fetch.mockRestore();
});

test('renders table headers after fetching data', async () => {
render(<Table />);

const header1 = await screen.findByText('S.No.');
const header2 = screen.getByText('Percentage Funded');
const header3 = screen.getByText('Amount Pledged');

expect(header1).toBeInTheDocument();
expect(header2).toBeInTheDocument();
expect(header3).toBeInTheDocument();
});

test('renders table rows with fetched data', async () => {
render(<Table />);

const firstCell = await screen.findByText('1');
const percentageCell = screen.getByText(/50%/i);
const amountCell = screen.getByText(/\$1,000/i);

expect(firstCell).toBeInTheDocument();
expect(percentageCell).toBeInTheDocument();
expect(amountCell).toBeInTheDocument();
});
});
38 changes: 38 additions & 0 deletions src/components/Pagination.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import React from "react";
import "../styles/Pagination.css";

const Pagination = ({ currentPage, totalPages, onPageChange }) => {
const handleClick = (pageNumber) => {
if (pageNumber !== currentPage) {
onPageChange(pageNumber);
}
};

return (
<nav aria-label="Pagination Navigation">
<div className="pagination">
<button
className="pagination-button"
onClick={() => handleClick(currentPage - 1)}
disabled={currentPage === 1}
aria-label="Previous Page"
>
&laquo;
</button>

<span className="pagination-current">{currentPage}</span>

<button
className="pagination-button"
onClick={() => handleClick(currentPage + 1)}
disabled={currentPage === totalPages}
aria-label="Next Page"
>
&raquo;
</button>
</div>
</nav>
);
};

export default Pagination;
83 changes: 83 additions & 0 deletions src/components/Table.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import React, { useEffect, useState } from "react";
import Pagination from "./Pagination";
import "../styles/Table.css";

const Table = () => {
const [tableData, setTableData] = useState([]);
const [error, setError] = useState(null);

const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 5;

const API_URL =
"https://raw.githubusercontent.com/saaslabsco/frontend-assignment/refs/heads/master/frontend-assignment.json";

const fetchTableData = async () => {
try {
const response = await fetch(API_URL);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setTableData(data);
} catch (error) {
setError(error.message);
}
};

useEffect(() => {
fetchTableData();
}, []);

const totalPages = Math.ceil(tableData.length / itemsPerPage);

const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = tableData.slice(indexOfFirstItem, indexOfLastItem);

const handlePageChange = (pageNumber) => {
setCurrentPage(pageNumber);
};

return (
<div className="table-container">
{error ? (
<p className="error-message">Error: {error}</p>
) : (
<>
<table className="data-table">
<thead className="table-head">
<tr className="table-row">
<th scope="col" className="table-header">S.No.</th>
<th scope="col" className="table-header">Percentage Funded</th>
<th scope="col" className="table-header">Amount Pledged</th>
</tr>
</thead>
<tbody className="table-body">
{currentItems.map((project, index) => (
<tr key={index} className="table-row">
<td className="table-cell">{project["s.no"]}</td>
<td className="table-cell">
{project["percentage.funded"]}%
</td>
<td className="table-cell">
${project["amt.pledged"].toLocaleString()}
</td>
</tr>
))}
</tbody>
</table>
{totalPages > 1 && (
<Pagination
currentPage={currentPage}
totalPages={totalPages}
onPageChange={handlePageChange}
/>
)}
</>
)}
</div>
);
};

export default Table;
13 changes: 13 additions & 0 deletions src/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
17 changes: 17 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
Loading