I need help with this code. It is a website that shows users on the screen and the button on the right should open the user information details in a modal. I can't get the information of the user I click on, to appear in the modal. Show me the last one.
web photo
Foto of the website
Foto of the modal
And this is my code
import { Modal } from "antd";
import 'antd/dist/antd.css';
import { useEffect, useState } from "react"
import { userApi } from "../api/userApi";
import { Usuario } from "../interfaces/fetchAllUserResponse";
export const List = () => {
const [users, setUsers] = useState<Usuario[]>([]);
const [currentPage, setCurrentPage] = useState(0);
const [isModalOpen, setIsModalOpen] = useState(false);
useEffect(() => {
// call API
userApi.get<Usuario[]>('/default/techJobMission')
.then( resp => {
setUsers( resp.data );
})
.catch( console.log )
}, []);
const filteredUsers = (): Usuario[] => {
return users.slice(currentPage, currentPage + 6);
}
const nextUser = () => {
setCurrentPage( currentPage + 5 )
}
const prevUser = () => {
if( currentPage > 0 ){
setCurrentPage( currentPage - 5 )
};
}
const renderItem = ({ _id, firstName, lastName, ticket, present }: Usuario) => {
const openModal = () => {
setIsModalOpen(true)
}
const handleOk = () => {
setIsModalOpen(false);
};
const handleCancel = () => {
setIsModalOpen(false);
};
return (
<tr key={ _id }>
<td >
{( present ? <img className="ticket" src="icons/ticket-green.svg"/> : <img className="ticket" src="icons/ticket-red.svg"/>)}
</td>
<td className="user">
<p className="encabezado">{firstName } {lastName}</p>
{( present ? <p className="estado">Ha entrado</p> : <p className="estado">No ha entrado</p> )}
</td>
<td className="id-user">
<p className="encabezado2">ID</p>
<p className="estado">{_id}</p>
</td>
<td className="ticket-td">
<p className="encabezado2">Nº de ticket</p>
<p className="estado">{ticket + 1}</p>
</td>
<td>
<button onClick={openModal} className="btn-modal"> <img src="icons/menu-modal.svg"/> </button>
<Modal open={isModalOpen} onOk={handleOk} onCancel={handleCancel} >
<p>{firstName}</p>
</Modal>
</td>
</tr>
)
}
return (
<>
<table className="table">
<tbody>
{
filteredUsers().map( renderItem )
}
</tbody>
</table>
<br />
<button onClick={ prevUser } className="paginacion">
<img src="icons/anterior.svg"/> Anterior
</button>
<button onClick={ nextUser } className="paginacion">
Siguiente <img src="icons/siguiente.svg"/>
</button>
</>
)
}
It's opening all of the modals.
You have multiple modals and one boolean value indicating if "the modal" is open or not. So either they're all open or they're all not open.
Instead of tracking a single boolean value, track something like an identifier for which modal to display. For example:
const [modalID, setModalID] = useState();
And:
const openModal = (id) => {
setModalID(id)
}
const handleCancel = () => {
setModalID(undefined);
};
Then pass that id to the function from your record:
onClick={() => openModal(_id)}
And use it to determine if the modal is open:
open={modalID === _id}
Related
I'm trying to get a value of list element by clicking on it, but the problem is that key, id, value not on a same element. I'll better show you. Here it is my list component:
import React, { useState, useEffect, useContext, useRef } from 'react';
import { Input } from '../';
import styles from "./Table.module.css";
import { Context } from "../../context/Context.js";
export const Table = (props) => {
const ref = useRef(null);
const [context, setContext] = useContext(Context);
const [search, setSearch] = useState("");
const [crypto, setCrypto] = useState([]);
const handleOnClick = (e, val) => { //THIS IS MY onClick FUNCTION
console.log("event",e.target.val)
console.log("ref",e.currentTarget.val);
setContext()//setContext((currentArray) => [...currentArray, inputValue])
};
useEffect(() => {
const fetchData = async () => {
await fetch(`https://api.coinstats.app/public/v1/coins?skip=0&limit=100¤cy=USD`)
.then((response) => {
return response.json();
})
.then((data) => {
setCrypto(data.coins)
})
};
fetchData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<div
{...props}
>
<h1>All Cryptocurrencies</h1>
<Input
type="text"
placeholder="Search..."
onChange={(e) => {
setSearch(e.target.value);
}}
/>
<table className={styles.table}>
<thead>
<tr>
<td>Rank</td>
<td>Name</td>
<td>Symbol</td>
<td>Total Supply</td>
<td>Market Cap</td>
<td>Price</td>
<td>Volume(24hrs)</td>
</tr>
</thead>
{/* Mapping all the cryptos */}
<tbody >
{/* Filtering to check for the searched crypto */}
{crypto
.filter((val) => {
return val.name.toLowerCase().includes(search.toLowerCase());
})
.map((val, id) => {
return (
<React.Fragment key={id}>
<tr id={id.toString()}>
<td>{val.rank}</td>
<td>
<a href={val.websiteUrl}>
<picture>
<img src={val.icon} alt="logo" width="30px" />
</picture>
</a>
<p>{val.name}</p>
</td>
<td className="symbol">{val.symbol}</td>
<td>${(val.totalSupply / 1000000).toFixed(0)} K</td>
<td>${(val.marketCap / 1000000000).toFixed(1)} B</td>
<td>${val.price < 0.01 ? val.price.toFixed(4) : val.price.toFixed(2) }</td>
<td>${(val.volume / 1000000000).toFixed(1)} B</td>
</tr>
</React.Fragment>//val.price.toFixed(4)
);
})}
</tbody>
</table>
</div>
);
};
And it looks like this:
So as you see I fetch the data from CoinGecko API. What do I expect: To get value (coin name f.e. "ethereum" by clicking on a list element)
Thank you in advance!
I have created a crud operation page. When I am searching for any data from page 1 then the search functionality works very well but when I am going to another page using pagination button and after that when I am going to search something then it will returns me a empty result. can anyone figure it out , what i am doing wrong or where I can make changes?
import Wrapper from '../Helpers/Wrapper';
import './Users.css';
import { useEffect, useRef, useState } from "react";
import Modal from "../Layout/Modal";
import Button from '../UI/Button';
import axios from "axios";
import ReactPaginate from 'react-paginate';
const Users = () => {
const searchRef = useRef();
const [users, setUsers] = useState([]);
const [editUser, setEditUser] = useState([]);
const [openModal, setOpenModal] = useState(false);
const [searchValue, setSearchValue] = useState();
const [title, setTitle] = useState("Add a new User");
const [offset, setOffset] = useState(0);
const [perPage, setPerPage] = useState(10);
const [pageCount, setPageCount] = useState(0);
const [apid, setApid] = useState(null);
// The ids of users who are removed from the list
const [ids, setIds] = useState([]);
const [isCheckAll, setIsCheckAll] = useState(false);
const getApiData = async () => {
const res = await axios.get('https://geektrust.s3-ap-southeast-1.amazonaws.com/adminui-problem/members.json');
const data = res.data;
setApid(data);
const postData = data.slice(offset, offset + perPage);
setUsers(postData);
setPageCount(Math.ceil(data.length / perPage))
}
useEffect(() => {
getApiData();
}, [offset]);
const deleteRecord = userId => {
const newUsersList = [...users];
const index = users.findIndex(user => user.id === userId);
newUsersList.splice(index, 1);
setUsers(newUsersList);
};
const errorHandler = () => {
setOpenModal(false);
};
const addUsermodal = () => {
setOpenModal(true);
};
const onCheckHandler = userRecord => {
const filtereduser = users.findIndex(record => record.id === userRecord.id);
if (filtereduser != -1) {
users[filtereduser] = userRecord;
} else {
const newUsersList = [userRecord, ...users];
setUsers(newUsersList);
}
}
const editRecord = (record) => {
setEditUser(record);
setOpenModal(true);
setTitle('Update User');
};
const searchList = () => {
const enteredSearchData = searchRef.current.value;
setSearchValue(enteredSearchData);
};
const handlePageClick = async (e) => {
const selectedPage = (e.selected * 10) % apid.length;
setOffset(selectedPage);
};
const selectUserRecord = event => {
const selectedId = event.target.value;
if (ids.includes(selectedId)) {
const newIds = ids.filter((id) => id !== selectedId);
setIds(newIds);
} else {
const newIds = [...ids];
newIds.push(selectedId);
setIds(newIds);
}
};
const removeSelected = event => {
const remainingUser = users.filter(
user => !ids.includes(user.id)
)
setUsers(remainingUser);
};
const selectAllVisibleUserRecord = event => {
setIsCheckAll(!isCheckAll);
const postData = users.slice(offset, offset + perPage);
setIds(postData.map(li => li.id));
getApiData();
if (isCheckAll) {
setIds([]);
}
};
const btnMT = {
marginTop: '20px'
}
return (
<Wrapper>
{openModal && (<Modal
title={title}
editUser={editUser}
onConfirm={errorHandler}
oncheck={onCheckHandler}
/>)}
<div className="panelWrapper">
<h1>Users</h1>
<div className="addUsers" onClick={addUsermodal}>
<img src="./plus.svg" alt="add" />
<span>Add new User</span>
</div>
<div className="searchData">
<div className="searchBox">
<label htmlFor="search">Search</label>
<input
id="search"
type="text"
ref={searchRef}
/>
</div>
<Button type={'button'} onClick={searchList}>Search</Button>
</div>
<div className="usersList">
<div className="tableWrapper">
<table>
<thead>
<tr>
<th>
<input
type="checkbox"
name="selectAll"
id="selectAll"
onChange={selectAllVisibleUserRecord}
/>
</th>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Role</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{users.filter(data => {
if (searchValue === '' || searchValue === undefined) {
return data;
} else if (data.name.toLowerCase().includes(searchValue.toLowerCase())) {
return data;
} else if (data.email.toLowerCase().includes(searchValue.toLowerCase())) {
return data;
} else if (data.role.toLowerCase().includes(searchValue.toLowerCase())) {
return data;
}
}).map((listdata) => (
<tr key={listdata.id} className={ids.includes(listdata.id) ? 'checked' : ''}>
<td>
<input
id={`custom-checkbox-${listdata.id}`}
type="checkbox"
value={listdata.id}
name={listdata.name}
onChange={selectUserRecord}
checked={ids.includes(listdata.id) ? true : false}
/>
</td>
<td>{listdata.id}</td>
<td>{listdata.name}</td>
<td>{listdata.email}</td>
<td>{listdata.role}</td>
<td>
<img src="./edit.svg" alt="edit" onClick={event => editRecord(listdata)} />
<img src="./delete.svg" alt="Delete" onClick={event => deleteRecord(listdata.id)} />
</td>
</tr>
))}
</tbody>
</table>
</div>
<div style={btnMT}>
<Button type={'button'} onClick={removeSelected}>Delete Selected</Button>
</div>
<ReactPaginate
previousLabel={"prev"}
nextLabel={"next"}
breakLabel={"..."}
breakClassName={"break-me"}
pageCount={pageCount}
pageRangeDisplayed={5}
onPageChange={handlePageClick}
containerClassName={"pagination"}
subContainerClassName={"pages pagination"}
activeClassName={"active"} />
</div>
</div>
</Wrapper>
);
}
export default Users;
I'm pretty new to javascript and react, and I have been following a tutorial on how to create an e-commerce website, but I'm having an issue getting my product page to load. My original ProductListScreen.js had worked fine, but I wanted to update my project to React Router 6, and now the page won't load. I'm getting a TypeError: Cannot read properties of undefined (reading 'map') error, and when I checked to see on what line the error is occurring it says that the problem is on line 105, which is where <tbody> is. I'm unsure of why I am getting this error as I have only updated my code. I would really appreciate any help or guidance as to why I might be getting this error.
Thank you!
Updated ProductListScreen.js
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useParams, useNavigate, useLocation } from 'react-router-dom';
import {
createProduct,
deleteProduct,
listProducts,
} from '../actions/productActions';
import LoadingBox from '../components/LoadingBox';
import MessageBox from '../components/MessageBox';
import {
PRODUCT_CREATE_RESET,
PRODUCT_DELETE_RESET,
} from '../constants/productConstants';
export default function ProductListScreen(props) {
const navigate = useNavigate();
const { pageNumber = 1 } = useParams();
const { pathname } = useLocation();
const sellerMode = pathname.indexOf('/seller') >= 0;
const productList = useSelector((state) => state.productList);
const { loading, error, products, page, pages } = productList;
const productCreate = useSelector((state) => state.productCreate);
const {
loading: loadingCreate,
error: errorCreate,
success: successCreate,
product: createdProduct,
} = productCreate;
const productDelete = useSelector((state) => state.productDelete);
const {
loading: loadingDelete,
error: errorDelete,
success: successDelete,
} = productDelete;
const userSignin = useSelector((state) => state.userSignin);
const { userInfo } = userSignin;
const dispatch = useDispatch();
useEffect(() => {
if (successCreate) {
dispatch({ type: PRODUCT_CREATE_RESET });
navigate(`/product/${createdProduct._id}/edit`);
}
if (successDelete) {
dispatch({ type: PRODUCT_DELETE_RESET });
}
dispatch(
listProducts({ seller: sellerMode ? userInfo._id : '', pageNumber })
);
}, [
createdProduct,
dispatch,
navigate,
sellerMode,
successCreate,
successDelete,
userInfo._id,
pageNumber,
]);
const deleteHandler = (product) => {
if (window.confirm('Are you sure to delete?')) {
dispatch(deleteProduct(product._id));
}
};
const createHandler = () => {
dispatch(createProduct());
};
return (
<div>
<div className="row">
<h1>Products</h1>
<button type="button" className="primary" onClick={createHandler}>
Create Product
</button>
</div>
{loadingDelete && <LoadingBox></LoadingBox>}
{errorDelete && <MessageBox variant="danger">{errorDelete}</MessageBox>}
{loadingCreate && <LoadingBox></LoadingBox>}
{errorCreate && <MessageBox variant="danger">{errorCreate}</MessageBox>}
{loading ? (
<LoadingBox></LoadingBox>
) : error ? (
<MessageBox variant="danger">{error}</MessageBox>
) : (
<>
<table className="table">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>PRICE</th>
<th>ACTIONS</th>
</tr>
</thead>
<tbody>
{products.map((product) => (
<tr key={product._id}>
<td>{product._id}</td>
<td>{product.name}</td>
<td>{product.price}</td>
<td>
<button
type="button"
className="small"
onClick={() =>
props.history.push(`/product/${product._id}/edit`)
}
>
Edit
</button>
<button
type="button"
className="small"
onClick={() => deleteHandler(product)}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</>
)}
</div>
);
}
Original ProductListScreen.js
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
createProduct,
deleteProduct,
listProducts,
} from '../actions/productActions';
import LoadingBox from '../components/LoadingBox';
import MessageBox from '../components/MessageBox';
import {
PRODUCT_CREATE_RESET,
PRODUCT_DELETE_RESET,
} from '../constants/productConstants';
export default function ProductListScreen(props) {
const sellerMode = props.match.path.indexOf('/seller') >= 0;
const productList = useSelector((state) => state.productList);
const { loading, error, products } = productList;
const productCreate = useSelector((state) => state.productCreate);
const {
loading: loadingCreate,
error: errorCreate,
success: successCreate,
product: createdProduct,
} = productCreate;
const productDelete = useSelector((state) => state.productDelete);
const {
loading: loadingDelete,
error: errorDelete,
success: successDelete,
} = productDelete;
const userSignin = useSelector((state) => state.userSignin);
const { userInfo } = userSignin;
const dispatch = useDispatch();
useEffect(() => {
if (successCreate) {
dispatch({ type: PRODUCT_CREATE_RESET });
props.history.push(`/product/${createdProduct._id}/edit`);
}
if (successDelete) {
dispatch({ type: PRODUCT_DELETE_RESET });
}
dispatch(listProducts({ seller: sellerMode ? userInfo._id : '' }));
}, [
createdProduct,
dispatch,
props.history,
sellerMode,
successCreate,
successDelete,
userInfo._id,
]);
const deleteHandler = (product) => {
if (window.confirm('Are you sure to delete?')) {
dispatch(deleteProduct(product._id));
}
};
const createHandler = () => {
dispatch(createProduct());
};
return (
<div>
<div className="row">
<h1>Products</h1>
<button type="button" className="primary" onClick={createHandler}>
Create Product
</button>
</div>
{loadingDelete && <LoadingBox></LoadingBox>}
{errorDelete && <MessageBox variant="danger">{errorDelete}</MessageBox>}
{loadingCreate && <LoadingBox></LoadingBox>}
{errorCreate && <MessageBox variant="danger">{errorCreate}</MessageBox>}
{loading ? (
<LoadingBox></LoadingBox>
) : error ? (
<MessageBox variant="danger">{error}</MessageBox>
) : (
<table className="table">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>PRICE</th>
<th>ACTIONS</th>
</tr>
</thead>
<tbody>
{products.map((product) => (
<tr key={product._id}>
<td>{product._id}</td>
<td>{product.name}</td>
<td>{product.price}</td>
<td>
<button
type="button"
className="small"
onClick={() =>
props.history.push(`/product/${product._id}/edit`)
}
>
Edit
</button>
<button
type="button"
className="small"
onClick={() => deleteHandler(product)}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
);
}
You are getting the error here:
{products.map((product) => (
//... your code ...//
))}
because, during the initial render products is undefined.
Solution:
{products && products.length && products.map((product) => (
//... your code ...//
))}
before you map, you should check undefined:
{products?.map((product) => ... )}
I am trying to build a search and sorting functionality for the table content. I don't want to use package as I am trying to learn and see how the react search work. I have the following that loads the content from payloads
import React, {useState, useEffect} from 'react'
import '../css/about.css';
import Pagination from '../components/Pagination'
function About() {
const [userData, setUserData] = useState([]);
const [loading , setLoading] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
const [postsPerPage, setPostsPerPage] = useState(5);
const [search, setSearch] = useState("");
async function getData()
{
let response = await fetch('https://api.github.com/users');
let data = await response.json();
// setUserData(data)
return data;
}
//call getData function
getData()
.then(data => console.log(data)
);//
useEffect(() => {
setLoading(true)
getData()
.then(
data => {
setUserData(data) }
)
.catch(error => {
console.log(error);
})
}, [])
// Get current posts
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const currentPosts = userData.slice(indexOfFirstPost, indexOfLastPost);
// changw page
const paginate = (pageNumber) => setCurrentPage(pageNumber);
// Search Table
const handleFilterChange = e => {
const value = e.target.value || undefined;
if( search !== "" && userData.login.indexOf(search.toLowerCase()) === -1 ) {
return null;
}
setSearch(value)
}
return (
<div className="container">
<div>
<input value={search}
onChange={handleFilterChange}
placeholder={"Search"}
/>
<table>
<thead>
<tr>
<td>id</td>
<td>avatar_url</td>
<td>events_url</td>
<td>followers_url</td>
<td>following_url</td>
<td>gists_url</td>
<td>gravatar_id</td>
<td>html_url</td>
<td>login</td>
<td>node_id</td>
<td>organizations_url</td>
<td>received_events_url</td>
<td>repos_url</td>
<td>site_admin</td>
<td>starred_url</td>
<td>subscriptions_url</td>
<td>type</td>
<td>url</td>
</tr>
</thead>
<tbody>
{
currentPosts.map((item, index) => (
<tr key={index}>
<td>{item.id}</td>
<td>{item.avatar_url}</td>
<td>{item.events_url}</td>
<td>{item.followers_url}</td>
<td>{item.following_url}</td>
<td>{item.gists_url}</td>
<td>{item.gravatar_id}</td>
<td>{item.html_url}</td>
<td>{item.login}</td>
<td>{item.node_id}</td>
<td>{item.organizations_url}</td>
<td>{item.received_events_url}</td>
<td>{item.repos_url}</td>
<td>{item.site_admin}</td>
<td>{item.starred_url}</td>
<td>{item.subscriptions_url}</td>
<td>{item.type}</td>
<td>{item.url}</td>
</tr>
))
}
</tbody>
</table>
<Pagination postsPerPage={postsPerPage} totalPosts={userData.length} paginate={paginate} />
</div>
</div>
)
}
export default About
The pagination code is listed below.
import React from 'react'
const Pagination = ({ postsPerPage, totalPosts, paginate }) => {
const pageNumbers = [];
for(let i = 1; i <= Math.ceil(totalPosts / postsPerPage); i++) {
pageNumbers.push(i);
}
return (
<div>
<ul className="pagination">
{pageNumbers.map(number => (
<li key={number} className="page-item">
<a onClick={() => paginate(number)}
href="#" className="page-link">
{number}
</a>
</li>
))}
</ul>
</div>
)
}
export default Pagination
I am think because I used .map within the tbody and the search isn't affecting the content. Though I have no error, only that nothing is displaying from search parameters.
I noticed you didn't create the function to handle the searching. You can use this generic approach which will search across the rows and the column and will match the cases.
function DataSearch(rows) {
const columns = rows[0] && Object.keys(rows[0]);
return rows.filter((row) =>
columns.some((column) => row[column].toString().toLowerCase().indexOf(search.toLowerCase()) > -1)
);
}
instantiate the function
const searchPosts = DataSearch(currentPosts);
Use the searchPosts on your .map function in tbody.
I am working on a React project, In that project I am trying to sorting. In my component I have
Two buttons. The first button is Change to Min and the second button is Change to Max.
And in the same component I am showing the data that is coming from the backend.
Now If I click the button the sorting logic state has to apply to the data what I am showing by
Using the map method.
This is list.js
import React, { useState, useEffect } from 'react';
import { Table, Button } from 'reactstrap';
import Aumservice from '../../service/aum-service';
import { MdEdit } from 'react-icons/md';
import { IconContext } from "react-icons";
const List = (props) => {
const [sortData, setSortData] = useState(null)
const [data, setData] = useState([])
useEffect(() => {
(async function () {
const response = await Aumservice.getAum()
const dataResponse = response.data.list.map(ele => ele.maxValue)
setSortData(dataResponse)
setData(response.data.list)
})()
}, [])
const sortAscending = () => {
let sortedData = sortData.sort((a, b) => a - b)
console.log(sortedData)
setData(sortedData)
}
const sortDescending = () => {
let sortedData = sortData.sort((a, b) => b - a)
setData(sortedData)
}
return (
<div>
<IconContext.Provider
value={{ size: '25px' }}
>
<Table bordered>
<thead>
<tr>
<th>So No</th>
<th>Min</th>
<th>Max</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{setData.map((currentValue, index) => {
return < tr key={index + 1} >
<th scope="row">{index + 1}</th>
<td>{currentValue.minValue}</td>
<td>{currentValue.maxValue}</td>
</tr>
})}
</tbody>
</Table>
</IconContext.Provider>
<div className='min pr-5'>
<Button onClick={sortAscending} className='primary'>Change to Min</Button>
</div>
<div className='max'>
<Button className='secondary'>Change to Max</Button>
</div>
</div >
)
}
export default List
If I am not clear with my doubt please put a comment.
If I get it right, you want your data to be sorted by maxValue, in a way that depends on which button is clicked (ascending/descending).
There is a typo in the mapping element, instead of setData.map((.. you need data.map((...
An onClick event must be added at the second button with the sortDescending function.
You do not need a second variable sortData for sorting your data, you can sort the existing list that you get from the response.
According to the above conclusions, I have edited your code:
import React, { useState, useEffect } from 'react';
import { Table, Button } from 'reactstrap';
import Aumservice from '../../service/aum-service';
import { MdEdit } from 'react-icons/md';
import { IconContext } from "react-icons";
const List = (props) => {
const [data, setData] = useState([])
useEffect(() => {
(async function () {
const response = await Aumservice.getAum()
setData(response.data.list)
})()
}, [])
const sortAscending = () => {
let copyData = JSON.parse(JSON.stringify(data));
// If you want to sort by minValue,just change accordingly the below properties
let sortedData = copyData.sort((a, b) => (a.maxValue > b.maxValue) ? 1 : -1);
console.log(sortedData)
setData(sortedData)
}
const sortDescending = () => {
let copyData = JSON.parse(JSON.stringify(data));
// If you want to sort by minValue,just change accordingly the below properties
let sortedData = copyData.sort((a, b) => (a.maxValue < b.maxValue) ? 1 : -1);
console.log(sortedData)
setData(sortedData)
}
return (
<div>
<IconContext.Provider
value={{ size: '25px' }}
>
<Table bordered>
<thead>
<tr>
<th>So No</th>
<th>Min</th>
<th>Max</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{data.map((currentValue, index) => {
return <tr key={index + 1} >
<th scope="row">{index + 1}</th>
<td>{currentValue.minValue}</td>
<td>{currentValue.maxValue}</td>
</tr>
})}
</tbody>
</Table>
</IconContext.Provider>
<div className='min pr-5'>
<Button onClick={sortAscending} className='primary'>Change to Min</Button>
</div>
<div className='max'>
<Button onClick={sortDescending} className='secondary'>Change to Max</Button>
</div>
</div >
)
}
export default List