How to make a component toggle by column - javascript

I can't figure out how to implement component switching. That is, first the timer component should be in USER 1 for a minute, then in USER 2 for a minute. And so on in a circle.
import "./App.css";
import React, { useEffect, useState } from "react";
import { Header } from "./components/Header";
import { getPadTime } from "../src/components/helpers/getPadTime";
import User from "./components/Users";
import { Timer } from "./components/Timer";
function App() {
const [users, setUsers] = useState([User[0], User[1]]);
const [timeLeft, setTimeLeft] = useState(2 * 60);
const [isCouting, setIsCouting] = useState(false);
const [count, setCount] = useState(2);
const minutes = getPadTime(Math.floor(timeLeft / 60));
const seconds = getPadTime(timeLeft - minutes * 60);
useEffect(() => {
const interval = setInterval(() => {
isCouting &&
setTimeLeft((timeLeft) => (timeLeft >= 1 ? timeLeft - 1 : 0));
}, 1000);
if (timeLeft === 0) {
setTimeLeft(2 * 60);
}
return () => clearInterval(interval);
}, [timeLeft, isCouting]);
const handleAdd = () => {
if (count < User.length) {
setUsers([...users, User[count]]);
setCount(count + 1);
} else {
alert("Users ended");
}
};
const handleRemove = () => {
if (count !== 0) {
setUsers((prevState) => {
const idx = users.length - 1;
return [...prevState.slice(0, idx), ...prevState.slice(idx + 1)];
});
setCount(count - 1);
} else if (count < 0) {
alert("You can only add a user");
}
};
const handleStart = () => {
if (timeLeft === 0) setTimeLeft(120);
setIsCouting(true);
};
const handleStop = () => {
setIsCouting(false);
};
const handleRestart = () => {
setTimeLeft(120);
setIsCouting(false);
};
return (
<div className="App">
<Header />
<div className="container">
<table className="table">
<thead className="move">
<th>MOVE</th>
{users.length == 0 ? (
<Timer minutes={minutes} seconds={seconds} />
) : (
[...Array(users.length)].map((index) => (
<Timer key={index} minutes={minutes} seconds={seconds} />
))
)}
</thead>
<thead className="thead">
<th className="main">PARAMETERS REQUIREMENTS</th>
{users.map((user) => (
<th className="trade_user" key={user.id}>
{user.name}
</th>
))}
</thead>
<tbody>
<tr>
<td className="main">
Availability of a set of measures that raise quality standards
manufacturing
</td>
{users.map((user) => (
<td className="trade_user" key={user.id}>
{user.complexesOfMeasures}
</td>
))}
</tr>
<tr>
<td className="main"> Lot production time, days</td>
{users.map((user) => (
<td className="trade_user" key={user.id}>
{user.productionPeriod}
</td>
))}
</tr>
<tr>
<td className="main">Warranty obligations, months</td>
{users.map((user) => (
<td className="trade_user" key={user.id}>
{user.warranty}
</td>
))}
</tr>
<tr>
<td className="main">Terms of payment</td>
{users.map((user) => (
<td className="trade_user" key={user.id}>
{user.paymentTerms}%
</td>
))}
</tr>
<tr>
<td className="main">
The cost of manufacturing a lot
</td>
{users.map((user) => (
<td className="trade_user cost" key={user.id}>
{user.cost}
</td>
))}
</tr>
<tr>
<td className="main">Actions:</td>
{users.map((user) => (
<td className="trade_user" key={user.id}>
{user.action}
</td>
))}
</tr>
</tbody>
</table>
</div>
<button onClick={handleAdd}>Add User</button>
<button onClick={handleRemove}> Delete User</button>
{isCouting ? (
<button onClick={handleStop}>Stop</button>
) : (
<button onClick={handleStart}>Start</button>
)}
<button onClick={handleRestart}>Restart</button>
</div>
);
}
A component with a timer, at first I thought to implement it through opacity in css, but I don’t understand how to attach it to a specific column.
import React from "react";
import { CgSandClock } from "react-icons/cg";
export const Timer = ({minutes, seconds}) => {
return (
<th>
<div className="move_time">
<span>{minutes}</span>
<span>:</span>
<span>{seconds}</span>
<div>
<CgSandClock size="1.5em" className="move_item_clock" />
</div>
</div>
</th>
);
};
enter image description here

Related

Filter function by name React

I need a function to filter by name, The data comes from my Laravel API, I wanted to make a filter on the screen to search for the account name. I am new to React.
import Table from "react-bootstrap/Table";
import axios from "axios";
import { Link } from "react-router-dom";
import { useState, useEffect } from "react";
import Form from "react-bootstrap/Form";
import Button from "react-bootstrap/Button";
const endpoint = "http://localhost:8000/api";
const AccountShow = () => {
const [accounts, setAccounts] = useState([]);
useEffect(() => {
getAllAccounts();
}, []);
const getAllAccounts = async () => {
const response = await axios.get(`${endpoint}/accounts`);
setAccounts(response.data);
};
const deleteAccount = async (id) => {
await axios.delete(`${endpoint}/account/${id}`);
getAllAccounts();
};
return (
<div className="d-grid gap-2">
<div className="row">
<div className="col-8">
<Form className="d-flex m-1">
<Form.Control
type="search"
placeholder="Filtro"
className="me-2"
aria-label="Search"
/>
<Button variant="outline-secondary">Search</Button>
</Form>
</div>
<div className="col-4">
<Link
to="/account/create"
className="col-11 btn btn-outline-primary m-1 "
>
Create
</Link>
</div>
</div>
<Table hover className="">
<thead>
<tr>
<th scope="col">#</th>
<th className="col-2" scope="col">
Nome
</th>
<th className="col-2" scope="col">
Razão Social
</th>
<th scope="col">Status da Conta</th>
<th scope="col">Setor</th>
<th scope="col">Segmento Atuacao</th>
<th scope="col">Natureza Juridica</th>
<th scope="col">Capital</th>
<th scope="col">Funcionarios</th>
<th className="text-center" scope="col">
Ações
</th>
</tr>
</thead>
<tbody>
{accounts.map((account) => (
<tr key={account.id}>
<th>{account.id}</th>
<td>{account.nome}</td>
<td>{account.razaoSocial}</td>
<td>{account.statusConta}</td>
<td>{account.setor}</td>
<td>{account.segmentoAtuacao}</td>
<td>{account.naturezaJuridica}</td>
<td>{account.capital}</td>
<td>{account.funcionarios}</td>
<td className="text-center">
<Link
to={`edit/${account.id}`}
className="btn btn-outline-warning"
>
Editar
</Link>
<button
onClick={() => deleteAccount(account.id)}
className="btn btn-outline-danger m-1"
>
Deletar
</button>
</td>
</tr>
))}
</tbody>
</Table>
</div>
);
};
export default AccountShow;
This is a correct way to filter.
import Table from "react-bootstrap/Table";
import axios from "axios";
import { Link } from "react-router-dom";
import { useState, useEffect } from "react";
import Form from "react-bootstrap/Form";
import Button from "react-bootstrap/Button";
const endpoint = "http://localhost:8000/api";
const AccountShow = () => {
const searchQuery = useState("");
const [accounts, setAccounts] = useState([]);
const [accountToShow, setAccountsToShow] = useState([]);
useEffect(() => {
setAccountsToShow(accounts.filter((account) => /*filter by a specific parameter here depending on what you want to filter it by; by the account.nome field?*/ account.nome.includes(searchQuery)));
}, [accounts, searchQuery]);
useEffect(() => {
getAllAccounts();
}, []);
const getAllAccounts = async () => {
const response = await axios.get(`${endpoint}/accounts`);
setAccounts(response.data);
};
const deleteAccount = async (id) => {
await axios.delete(`${endpoint}/account/${id}`);
getAllAccounts();
};
return (
<div className="d-grid gap-2">
<div className="row">
<div className="col-8">
<Form className="d-flex m-1">
<Form.Control
onChange={({target}) => setSearchQuery(target.value)}
value={searchQuery}
type="search"
placeholder="Filtro"
className="me-2"
aria-label="Search"
/>
<Button variant="outline-secondary">Search</Button>
</Form>
</div>
<div className="col-4">
<Link
to="/account/create"
className="col-11 btn btn-outline-primary m-1 "
>
Create
</Link>
</div>
</div>
<Table hover className="">
<thead>
<tr>
<th scope="col">#</th>
<th className="col-2" scope="col">
Nome
</th>
<th className="col-2" scope="col">
Razão Social
</th>
<th scope="col">Status da Conta</th>
<th scope="col">Setor</th>
<th scope="col">Segmento Atuacao</th>
<th scope="col">Natureza Juridica</th>
<th scope="col">Capital</th>
<th scope="col">Funcionarios</th>
<th className="text-center" scope="col">
Ações
</th>
</tr>
</thead>
<tbody>
{accountsToShow.map((account) => (
<tr key={account.id}>
<th>{account.id}</th>
<td>{account.nome}</td>
<td>{account.razaoSocial}</td>
<td>{account.statusConta}</td>
<td>{account.setor}</td>
<td>{account.segmentoAtuacao}</td>
<td>{account.naturezaJuridica}</td>
<td>{account.capital}</td>
<td>{account.funcionarios}</td>
<td className="text-center">
<Link
to={`edit/${account.id}`}
className="btn btn-outline-warning"
>
Editar
</Link>
<button
onClick={() => deleteAccount(account.id)}
className="btn btn-outline-danger m-1"
>
Deletar
</button>
</td>
</tr>
))}
</tbody>
</Table>
</div>
);
};
export default AccountShow;
You can filter data using
useMemo()
const [accounts, setAccounts] = useState([]);
const [query, setQuery] = useState('');
const filterData = useMemo(() => {
if (accounts && accounts?.length > 0) {
return accounts.filter(item =>
item?.name
.toLocaleLowerCase('en')
.includes(query.trim().toLocaleLowerCase('en')),
);
}
}, [accounts, query]);
you can set query using textbox change event

How can I reduce the quantity with delivery button with react js?

As you can see in the react code, I am trying to reduce the quantity, but I struggle to do it in react. what I want is if click button then quantity should be reduced 1 by 1.
I don't understand what should I do here.
const ManageInventory = () => {
const [products, setProducts] = useProducts();
const handleDelevery = id => {
const handleDelivery = event => { event.preventDefault();
const deliveryInventoryItem = inventoryItem.quantity(quantity-1);
}
const handleDelete = id => {
const proceed = window.confirm('Are Your Sure?');
if(proceed){
const url =`http://localhost:5000/product/${id}`;
fetch(url, {
method: 'DELETE'
})
.then(res => res.json())
.then(data => {
console.log(data);
const remaining = products.filter(product => product._id !==id);
setProducts(remaining);
})
}
}
return (
<div className=''>
<h2 className='product-title'>All Products {products.length} </h2>
<div>
</div>
<div>
<Table striped bordered hover variant="dark">
<thead>
<tr>
<th>Image</th>
<th>Prodct Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Supplier</th>
<th colSpan={2}>Edit</th>
</tr>
</thead>
<tbody>
{
products.map(product => <tr
key={product._id}
product={product}>
<td><img src={product.img} alt="" /> </td>
<td>{product.name}</td>
<td> {product.price}</td>
<td>{product.quantity}</td>
<td>{product.supplier}</td>
<td><button className='manage-btn' onClick={()=> handleDelete(product._id)}>Delete</button></td>
<td><button className='manage-btn' onClick={()=> handleDelevery()}>Delivered</button></td>
</tr>
)
}
</tbody>
</Table>
</div>
<button className='add-product-link'><Link to='/addproduct'>Add Product</Link></button>
</div>
);
};

Add search dropdown for React table in JHipster

I have this React table in JHipster project:
<div className="table-responsive">
{activePairsList && activePairsList.length > 0 ? (
<Table responsive>
<thead>
<tr>
<th className="hand" onClick={sort('id')}>
ID <FontAwesomeIcon icon="sort" />
</th>
<th className="hand" onClick={sort('exchangeId')}>
Exchange Id <FontAwesomeIcon icon="sort" />
</th>
...........
<th />
</tr>
</thead>
<tbody>
{activePairsList.map((activePairs, i) => (
<tr key={`entity-${i}`} data-cy="entityTable">
<td>
<Button tag={Link} to={`${match.url}/${activePairs.id}`} color="link" size="sm">
{activePairs.id}
</Button>
</td>
<td>{activePairs.exchangeId}</td>
</tr>
))}
</tbody>
</Table>
) : (
!loading && <div className="alert alert-warning">No Active Pairs found</div>
)}
</div>
I would like to add search functionality for this table. I want to add Filter by exchange to be present and when any exchange is selected the table should be filtered to show only data for the selected exchange. Do you know how this can be implemented?
I've worked on your issue in stackblitz. I create a link to a simple sample of what you want you can check it here.
I've added an input to filter data is passing to the table on input changes. Hope you find it useful.
I prepared a ReactJS/Typescript solution and implemented it on the JHipster 7.
NOTE: if you have no active-pairs entity, apply the below steps.Else continue from step 4.
First of all, create a monolith web project with JHipster 7 & ReactJS.
Create an entity of ActivePairs with JDL Studio and download
the JDL file from the JDL Studio. (activepairs-jdl.jdl)
If you want to pagination add this expression in your jdl file : paginate all with pagination
Copy the activepairs-jdl.jdl file to the root folder of your
project.
Open a terminal on the root folder of your project and write below command:
jhipster jdl activepairs-jdl.jdl
Go this path in your project :
src>main>webapp>app>entities>active-pairs>active-pairs.tsx
Copy the below code and paste it in your active-pairs.tsx file.
import { connect } from 'react-redux';
import { Link, RouteComponentProps } from 'react-router-dom';
import { Button, Col, Row, Table } from 'reactstrap';
import { ICrudGetAllAction, ICrudSearchAction } from 'react-jhipster';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import { IRootState } from 'app/shared/reducers';
import { getEntities } from './active-pairs.reducer';
import { IActivePairs } from 'app/shared/model/active-pairs.model';
import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants';
export interface IActivePairsProps extends StateProps, DispatchProps, RouteComponentProps<{ url: string }> { }
export const ActivePairs = (props: IActivePairsProps) => {
useEffect(() => {
props.getEntities();
}, []);
const { activePairsList, match, loading = true } = props;
const myDataSource = props.activePairsList;
const [myActivePairsList, setActivePairsList] = useState(props.activePairsList);
const [dropdownList, setDropdownList] = useState([])
const [focus, setFocus] = useState(false)
const [searchValue, setSearchValue] = useState('')
const [arrOfSelectedExId, setArrOfSelectedExId] = useState([])
useEffect(() => {
const unrepeated = activePairsList.reduce((acc, curr) => {
if (acc.find(item => item.exchangeId === curr.exchangeId)) {
return acc
}
return acc.concat(curr)
}, [])
const regexes = [`${searchValue}`];
const filtered = unrepeated.filter(item => regexes.some(regex => item.exchangeId.match(regex)));
setDropdownList(filtered);
setActivePairsList(activePairsList);
}, [searchValue, activePairsList])
useEffect(() => {
if (arrOfSelectedExId.length) {
setActivePairsList(myDataSource.filter(activePairs => {
return arrOfSelectedExId.includes(activePairs.exchangeId)
}))
} else {
setActivePairsList(myDataSource)
}
}, [arrOfSelectedExId])
return (
<div>
<input value={searchValue} onFocus={() => setFocus(true)} onBlur={(e) => setFocus(false)} onChange={e => setSearchValue(e.target.value)} />
{(dropdownList.length !== 0) && focus && (<div className="dropdown-parent">
{
dropdownList.map((item, i) => {
return <div key={'drp' + i} className={arrOfSelectedExId.includes(item.exchangeId) ? 'selected' : ''} onMouseDown={(e) => {
e.preventDefault()
setArrOfSelectedExId(prev => {
if (prev.includes(item.exchangeId)) {
return prev.filter(x => x !== item.exchangeId)
} else {
return prev.concat(item.exchangeId)
}
})
// setSearchValue(item.exchangeId)
}}>{item.exchangeId}</div>
})
}
</div>)}
<h2 id="active-pairs-heading">
Active Pairs
<Link to={`${match.url}/new`} className="btn btn-primary float-right jh-create-entity" id="jh-create-entity">
<FontAwesomeIcon icon="plus" />
Create new Active Pairs
</Link>
</h2>
<div className="table-responsive">
{myActivePairsList && myActivePairsList.length > 0 ? (
<Table responsive>
<thead>
<tr>
<th>ID</th>
<th>Exchange Id</th>
<th />
</tr>
</thead>
<tbody>
{myActivePairsList.map((activePairs, i) => (
<tr key={`entity-${i}`}>
<td>
<Button tag={Link} to={`${match.url}/${activePairs.id}`} color="link" size="sm">
{activePairs.id}
</Button>
</td>
<td>{activePairs.exchangeId}</td>
<td className="text-right">
<div className="btn-group flex-btn-group-container">
<Button tag={Link} to={`${match.url}/${activePairs.id}`} color="info" size="sm">
<FontAwesomeIcon icon="eye" /> <span className="d-none d-md-inline">View</span>
</Button>
<Button tag={Link} to={`${match.url}/${activePairs.id}/edit`} color="primary" size="sm">
<FontAwesomeIcon icon="pencil-alt" /> <span className="d-none d-md-inline">Edit</span>
</Button>
<Button tag={Link} to={`${match.url}/${activePairs.id}/delete`} color="danger" size="sm">
<FontAwesomeIcon icon="trash" /> <span className="d-none d-md-inline">Delete</span>
</Button>
</div>
</td>
</tr>
))}
</tbody>
</Table>
) : (
!loading && <div className="alert alert-warning">No Active Pairs found</div>
)}
</div>
</div>
);
};
const mapStateToProps = ({ activePairs }: IRootState) => ({
activePairsList: activePairs.entities,
loading: activePairs.loading,
});
const mapDispatchToProps = {
getEntities,
};
type StateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof mapDispatchToProps;
export default connect(mapStateToProps, mapDispatchToProps)(ActivePairs);
copy below css codes in your app.scss file :
h1,
p {
font-family: sans-serif;
}
.selected {
background-color: rgb(190, 188, 188);
}
.dropdown-parent {
max-height: 80px;
width: 200px;
overflow-y: scroll;
border: 1px solid black;
background-color: white;
position: absolute;
}
Run this command ./mvnw
You should see a search box at the top of your table.
As you see I selected 98 and It listed just the rows which have the
values of ExchangeID is 98
Thanks.

Update input label which is render by array map in REACTJS

Hope you guys are fine.
I have the next code for dynamically show the quantity of each selected product
import React, { useState, useEffect } from 'react';
import db from '../firebase';
//const Swal = window.Swal;
const NewSale = () => {
const [products, setProducts] = useState([]);
const [selectedProducts, setSelectedProducts] = useState([]);
useEffect(() => {
if(products.length === 0){
db.collection('products').get().then((querySnapshot) => {
const docs = [];
querySnapshot.forEach((doc) => {
docs.push({
id: doc.id,
...doc.data()
});
});
docs.sort((a, b)=> a.name.localeCompare(b.name));
setProducts(docs);
});
}
});
const handleSelectChange = (e) => {
const value = e.target.value;
if(value){
const selectedProduct = products.filter(item => item.id === value)[0];
setSelectedProducts(selectedProducts => [...selectedProducts, {
id: value,
name: selectedProduct.name,
quantity: 1
}]);
}
}
const handleRangeChange = (target, index) => {
const currentValue = parseInt(target.value);
let currentArrayValue = selectedProducts;
currentArrayValue[index].quantity = currentValue;
setSelectedProducts(currentArrayValue);
}
const handleCancelButton = () => {
setSelectedProducts([]);
}
return (
<React.Fragment>
<div className='container'>
<h1 className='display-3 text-center'>New Sale</h1>
<div className='row'>
<div className='col'>
<div className='mb-3'>
<label htmlFor='product' className='form-label fs-3'>Service</label>
<select id='product' onChange={handleSelectChange} className='form-select form-select-lg' multiple aria-label='multiple select service'>
{products.length !== 0?
products.map(item => <option key={item.id} value={item.id}>{item.name}</option>) : <option>No product registered</option>
}
</select>
</div>
</div>
</div>
<div className='row mt-4'>
<div className='col'>
<table className='table caption-top'>
<caption>Sell List</caption>
<thead>
<tr>
<th scope='col'>#</th>
<th scope='col'>Product</th>
<th scope='col'>Quantity</th>
</tr>
</thead>
<tbody>
{selectedProducts.length !== 0?
selectedProducts.map((item, index) => (
<tr key={index}>
<th scope='row'>{(index + 1)}</th>
<td>{item.name}</td>
<td>
<label htmlFor={`customRange-${index}`} className='form-label'>{item.quantity} Units</label>
<input
type='range'
className='form-range'
value={item.quantity}
onChange={({target}) => handleRangeChange(target, index)}
min='1'
max='100'
step='1'
id={`customRange-${index}`}/>
</td>
</tr>
)) :
<tr>
<th className='text-center' colSpan='3'>Nothing selected!</th>
</tr>
}
</tbody>
</table>
</div>
</div>
<div className='row mt-2'>
<div className='col'>
<button className='btn btn-success'>Save</button>
</div>
<div className='col'>
<button className='btn btn-warning' onClick={handleCancelButton}>Cancel</button>
</div>
</div>
</div>
</React.Fragment>
)
};
export default NewSale;
The code shows this... I do not know if I'm allowed to do this kind of operations because I'm adding events every time I select a product so, I'm not sure this is the best way to do it.
And the problem is that I'm getting this unexpected result,
What I want to do is show the current Quantity for each selected item,
Thanks!!

if ternario does not work, function has value but never used says

I am new with programing and I want to use if ternario, but it doesn't work. I have two functions and I create a third function to show one of them or the other. It is an application in ReactJS. Below is the code:
import { Table } from "react-bootstrap";
import { Link } from "react-router-dom";
import { useCartContext } from "../../Context/CartContext";
const emptyCart = () => {
return(
<>
<div>
<h3>The Cart is empty</h3>
<p>
Return to home to see our products
</p>
<Link to='/' ><button className="btn btn-info"> Home </button></Link>
</div>
</>
);
};
const CartFunction = () => {
const { list, totalPrice } = useCartContext();
return (
<Table striped hover>
<thead>
<tr>
<th>Product</th>
<th>Title</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{list.map((varietal) => (
<tr key={varietal.id}>
<td>
<img
src={varietal.pictureUrl}
alt='img'
style={{ width: "82px" }}
/>
</td>
<td>{varietal.title}</td>
<td>{varietal.count}</td>
<td>${varietal.price}</td>
</tr>
))}
</tbody>
<thead>
<tr>
<td colSpan="3">Total</td>
<td>${totalPrice()}</td>
</tr>
</thead>
</Table>
);
};
const CartComponent = () => {
const { list } = useCartContext();
return (
<>
{list.length !== 0 ? <CartFunction /> : <emptyCart />}
</>
);
};
export default CartComponent;
Visual Code it says that emptyCard has a value but it is never used. If there is someone that could help me I would appreciate it. Cheers

Categories

Resources