Export checked element as csv file - javascript

I'm trying to get only checked items saved in an array So that I'm going to export it as a CSV file. need help, that's my sandbox below;
https://codesandbox.io/s/laughing-bush-5fvl7b?file=/src/App.js

You can save the selected items id in state. Have a look:
import { useState } from "react";
import { CategoriesData } from "../data";
import "./styles.css";
export default function App() {
const [selectedIds, setSelectedIds] = useState([]);
return (
<div className="App">
<table id="categories">
<thead>
<tr id="titres">
<td className="input-check">
<input type="checkbox" className="checkbox" />
</td>
<td>CATEGORIES</td>
<td>DESCRIPTION</td>
</tr>
</thead>
<tbody>
{CategoriesData.map((category, index) => (
<tr
id={`element-${index}`}
key={category._id}
className={
selectedIds.includes(category.id) ? "product active" : "product"
}
>
<td className="input-check">
<input
type="checkbox"
className="checkbox"
onClick={(e) => {
var selected = e.target.checked;
if (selected) {
setSelectedIds([...selectedIds, category.id]);
} else {
setSelectedIds([
...selectedIds.filter((x) => x !== category.id)
]);
}
}}
/>
</td>
<td>{category.designation}</td>
<td id="category-desc">{category.description}</td>
</tr>
))}
</tbody>
</table>
</div>

Related

MySQL / React Application - TypeError: .map is not a function

Im working on a react application using MySQL.
On my page which includes a list of serveral cars from my database i got the following error:
Server Error
TypeError: fahrzeugData.map is not a function
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
.next\server\pages\fahrzeuge.js (34:24) # FahrzeugList
32 | </thead>
33 | <tbody className={styles.tbody}>
> 34 | {fahrzeugData.map((fzData, index) => (
| ^
35 | <tr key={index}>
36 | <td className={styles.th}>{index + 1}</td>
37 | <td className={styles.th}>{fzData.brutto}</td>
Call Stack
Function.getInitialProps
.next\server\pages\_document.js (150:43)
My js file looks like this:
import React from "react";
import Header from "./Header";
import Link from "next/link";
import { useRouter } from "next/router";
import styles from "../styles/FahrzeugList.module.css";
import axios from "axios";
function FahrzeugList({ fahrzeugData }) {
const router = useRouter();
const deleteFahrzeug = async (id) => {
let fahrzeugliste_t5 = await axios.delete(`http://localhost:3000/api/fahrzeug/${id}`);
router.push("/fahrzeuge");
};
return (
<>
<Header />
<table className={styles.table}>
<thead className={styles.thead}>
<tr>
<th className={styles.th}>FahrzeugId</th>
<th className={styles.th}>brutto</th>
<th className={styles.th}>erstzulassung</th>
<th className={styles.th}>fahrzeugnummer</th>
<th className={styles.th}>kilometer</th>
<th className={styles.th}>modelljahr</th>
<th className={styles.th}>netto</th>
<th className={styles.th}>reserviert</th>
<th className={styles.th}>sitzer</th>
<th className={styles.th}>sonstiges</th>
<th className={styles.th}>tuev</th>
<th className={styles.th}>Actions</th>
</tr>
</thead>
<tbody className={styles.tbody}>
{fahrzeugData.map((fzData, index) => (
<tr key={index}>
<td className={styles.th}>{index + 1}</td>
<td className={styles.th}>{fzData.brutto}</td>
<td className={styles.th}>{fzData.erstzulassung}</td>
<td className={styles.th}>{fzData.fahrzeugnummer}</td>
<td className={styles.th}>{fzData.kilometer}</td>
<td className={styles.th}>{fzData.modelljahr}</td>
<td className={styles.th}>{fzData.netto}</td>
<td className={styles.th}>{fzData.reserviert}</td>
<td className={styles.th}>{fzData.sitzer}</td>
<td className={styles.th}>{fzData.sonstiges}</td>
<td>
<button
className={styles.delete}
onClick={() => deleteFahrzeug(fzData.fz_id)}
>
Delete
</button>
<button className={styles.update}>
<Link href={`/fahrzeuge/${fzData.fz_id}`}>Update</Link>
</button>
</td>
</tr>
))}
</tbody>
</table>
<div className={styles.addFahrzeugCenter}>
<button className={styles.addFahrzeug}>
<Link href={`/addFahrzeug`}>addFahrzeug</Link>
</button>
</div>
</>
);
}
export default FahrzeugList;
Here is the js code where the FahrzeugList is used:
import FahrzeugList from "../components/FahrzeugList";
function fahrzeuge({ fahrzeugliste_t5 }) {
console.log("fahrzeugliste_t5", fahrzeugliste_t5);
return (
<div>
<FahrzeugList fahrzeugData={fahrzeugliste_t5} />
</div>
);
}
export async function getServerSideProps() {
const res = await fetch("http://localhost:3000/api/fahrzeug");
const fahrzeugliste_t5 = await res.json();
return {
props: { fahrzeugliste_t5 },
};
}
export default fahrzeuge;
And my database looks basically like this:
Adding new Cars to the list works perfectly from a different screen but displaying the list doesnt work. The Documentation for .map() function didnt help me.

how to disable a button if more than one or no checkbox is checked in React JS

I have a table where the first column has a checkbox in each row. I want to disable a button if more than one checkbox is selected or no check box is checked. It should be active only if 1 checkbox is checked
import React, { useState } from "react";
import "./styles.css";
function Example() {
const [boxes, setBoxes] = useState([]);
function handleChange(e) {
const {
parentNode: { children }
} = e.target;
const index = [...children].indexOf(e.target);
const newState = [...boxes];
newState[index] = !newState[index];
setBoxes(newState);
}
function isDisabled() {
const len = boxes.filter((box) => box).length;
return len === 0 || len > 1;
}
return (
<div className="App">
<button disabled={isDisabled()}>Click Me</button>
<table>
<thead>
<th>One</th>
<th>Two</th>
<th>Three</th>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" onChange={handleChange} />
</td>
<td> two data</td>
<td> three data</td>
</tr>
<tr>
<td>
<input type="checkbox" onChange={handleChange} />
</td>
<td> two data</td>
<td> three data</td>
</tr>
<tr>
<td>
<input type="checkbox" onChange={handleChange} />
</td>
<td> two data</td>
<td> three data</td>
</tr>
</tbody>
</table>
</div>
);
}
export default Example;
I was able to make this work if all the checkboxes are in the same parent node. But in the case of a table, each checkbox is in a separate row.
You can give them all the checkboxes one name and this solution will work just fine
import React, { useState } from "react";
function Example() {
const [btnStatus, setBtnStatus] = useState(true);
function handleChange(e) {
const elements = document.getElementsByName('checkbox');
let checkedCount = 0;
elements.forEach((element)=>{
if(element.checked){
checkedCount ++;
}
})
if(checkedCount > 1 || checkedCount === 0){
setBtnStatus(true)
}else{
setBtnStatus(false)
}
}
return (
<div className="App">
<button disabled={btnStatus}>Click Me</button>
<table>
<thead>
<th>One</th>
<th>Two</th>
<th>Three</th>
</thead>
<tbody>
<tr>
<td>
<input name="checkbox" type="checkbox" onChange={handleChange} />
</td>
<td> two data</td>
<td> three data</td>
</tr>
<tr>
<td>
<input name="checkbox" type="checkbox" onChange={handleChange} />
</td>
<td> two data</td>
<td> three data</td>
</tr>
<tr>
<td>
<input name="checkbox" type="checkbox" onChange={handleChange} />
</td>
<td> two data</td>
<td> three data</td>
</tr>
</tbody>
</table>
</div>
);
}
export default Example;
You can assign ids to the checkboxes and follow them like this.
import React, { useState } from "react";
function Example() {
const [boxes, setBoxes] = useState({});
function handleChange(e) {
const {
target: { id, checked }
} = e;
setBoxes({ ...boxes, [id]: checked });
}
function isDisabled() {
const { length } = Object.values(boxes).filter(Boolean);
return length !== 1;
}
return (
<div className="App">
<button disabled={isDisabled()}>Click Me</button>
<table>
<thead>
<th>One</th>
<th>Two</th>
<th>Three</th>
</thead>
<tbody>
<tr>
<td>
<input id="1" type="checkbox" onChange={handleChange} />
</td>
<td> two data</td>
<td> three data</td>
</tr>
<tr>
<td>
<input id="2" type="checkbox" onChange={handleChange} />
</td>
<td> two data</td>
<td> three data</td>
</tr>
<tr>
<td>
<input id="3" type="checkbox" onChange={handleChange} />
</td>
<td> two data</td>
<td> three data</td>
</tr>
</tbody>
</table>
</div>
);
}
export default Example;
Your initial test (with all checkboxes in the same parent node) was working because you are relying that they are all in the same parent node here:
const {
parentNode: { children }
} = e.target;
where "children" are the actual checkboxes. In the table example, each checkbox's parent has only one child.
I would suggest a more flexible solution like below, sending the checkbox index as a parameter to the onChange handler:
import React, { useState } from "react";
// use props to determine the number of records
function Example(props) {
// make sure initial state is known and false
const [boxes, setBoxes] = useState(new Array(props.recordsNo).fill(false));
// index - the index of the checkbox
function handleChange(index) {
const newState = [...boxes];
newState[index] = !newState[index];
setBoxes(newState);
}
function isDisabled() {
const len = boxes.filter((box) => box).length;
return len === 0 || len > 1;
}
// records will probably come through props => generate here an example
const records = [...Array(props.recordsNo).keys()];
// generate records display
const rows = records.map((value, i) => {
return (
<tr>
<td>
<input type="checkbox" onChange={() => handleChange(i)} />
</td>
<td> {i}</td>
<td> two data</td>
<td> three data</td>
</tr>
)
})
return (
<div className="App">
<button disabled={isDisabled()}>Click Me</button>
<table>
<thead>
<th>One</th>
<th>Two</th>
<th>Three</th>
</thead>
<tbody>
{rows}
</tbody>
</table>
</div>
);
}
export default Example;

How to define the length of the array when using map function and display the rows which have data?

I have created a button with the collapse effect and In that creating a simple table then I created an excel file and in that created a two table one display the button content and second table display the table content. when I run my code then an unlimited button is created and only 3 buttons display the data which I have stored in the table.
Here is my code:
import React, { useState } from 'react'
import { Table } from 'react-bootstrap'
import * as XLSX from 'xlsx'
import Accordion from './component/accordion'
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome'
import { faTrashAlt } from '#fortawesome/free-solid-svg-icons'
import './App.css'
function App() {
const[items, setItems] = useState([])
const readExcel=(file) => {
const promise = new Promise((resolve, reject)=>{
const fileReader = new FileReader();
fileReader.readAsArrayBuffer(file);
fileReader.onload=(e)=>{
const bufferArray = e.target.result;
const wb = XLSX.read(bufferArray, {type: "buffer"});
const wsname = wb.SheetNames[0];
const ws = wb.Sheets[wsname];
const data = XLSX.utils.sheet_to_json(ws);
resolve(data);
};
fileReader.onerror=(error) => {
reject(error);
};
});
promise.then((d)=>{
setItems(d);
console.log(d)
});
};
return(
<div className="container-fluid">
<section className="heading">
<h4>Products Details</h4>
<input type="file" className="input-field" name="Upload File" onChange={(e) =>{
const file=e.target.files[0];
readExcel(file);
}} />
</section>
{items.map((d) => (
<Accordion
title={
<tr key={d.ID} className="btn-heading">
<td style={{padding: "0px 36px"}}>{d.ID}</td>
<td style={{padding: "0px 16px"}}>{d.Mail}</td>
<td style={{padding: "0px 67px"}}>{d.Name}</td>
<td style={{padding: "0px 3px"}}>{d.PhoneNo}</td>
<td style={{padding: "0px 98px"}}>{d.City}</td>
<td style={{padding: "0px 6px"}}>{d.Date}</td>
<td style={{padding: "0px 120px"}}>{d.Time}</td>
</tr>
}
content={
<div>
<p className="header">
<span className="header-content">Shipping Address:</span>
292 Naqshband Colony. Near rabbania Mosque. Multan
</p>
<Table size="sm">
<thead>
<tr>
<th>#</th>
<th style={{width:"15%",textAlign:"center"}}>Article No</th>
<th style={{width:"30%"}}>Product Name</th>
<th style={{width:"20%" ,textAlign:"center"}}>Quantity</th>
<th style={{width:"15%" ,textAlign:"center"}}>Price</th>
<th style={{width:"15%" ,textAlign:"center"}}>Total Amount</th>
</tr>
</thead>
<tbody>
{items.map((d) => (
<tr key={d.ArticleNo}>
<colgroup>
<FontAwesomeIcon icon={faTrashAlt} />
</colgroup>
<td>{d.ArticleNo}</td>
<td style={{textAlign:"left"}}> {d.ProductName}</td>
<td>{d.Quantity}</td>
<td>{d.Price}</td>
<td>{d.TotalAmount}</td>
</tr>
))}
</tbody>
</Table>
</div>
}
/>
))}
</div>
);
}
export default App;
And here is my excel file which I have created two tables:
Excel File Tables
here is the output of my project the unlimited buttons:
Code Output

.map() function and deleting a row from a table with ReactJS

I'm having a problem wrapping my head around the .map() function as it relates to ReactJS. In practice, I have a table onto which I can add rows, but deleting a row by passing the index of the row is just not working. Here's what I have; can anyone clear up what I'm doing wrong?
import React from 'react';
import { render } from 'react-dom';
class CommentList extends React.Component {
constructor(props) {
super(props);
this.state = {
comments: []
};
this.handleCommentDelete = this.handleCommentDelete.bind(this);
}
handleCommentDelete(i) {
alert('i = ' + i);
let comments = [...this.state.comments];
comments.splice(i, 1);
this.setState({
comments: comments
});
}
render() {
return (
<table className="commentList">
<thead>
<tr>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
<th></th>
</tr>
</thead>
<tbody>
{
this.props.data.map((comment, i) => {
return (
<tr className="comment" key={i}>
<td className="commentId">{comment.Id}</td>
<td className="commentName">{comment.Name}</td>
<td className="commentPhone">{comment.Phone}</td>
<td className="commentEmail">{comment.Email}</td>
<td className="commentCRUD">
<a onClick={(i) => this.handleCommentDelete(i)}>
<i className="fa fa-trash" />
</a>
</td>
</tr>
);
})
}
</tbody>
</table>
);
}
}
export default CommentList;
Thanks in advance!
You are passing the index i, not the right way. Also i would prefer to pass id rather than index. Here is how you can do that:
import React from 'react';
import { render } from 'react-dom';
class CommentList extends React.Component {
constructor(props) {
super(props);
this.state = {
comments: []
};
this.handleCommentDelete = this.handleCommentDelete.bind(this);
}
handleCommentDelete(id) {
let comments = this.state.comments.filter(comment => comment.id !== id);
this.setState({
comments: comments
});
}
render() {
return (
<table className="commentList">
<thead>
<tr>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
<th></th>
</tr>
</thead>
<tbody>
{
this.props.data.map(comment => {
return (
<tr className="comment" key={comment.Id}>
<td className="commentId">{comment.Id}</td>
<td className="commentName">{comment.Name}</td>
<td className="commentPhone">{comment.Phone}</td>
<td className="commentEmail">{comment.Email}</td>
<td className="commentCRUD">
<a onClick={() => this.handleCommentDelete(comment.Id)}>
<i className="fa fa-trash" />
</a>
</td>
</tr>
);
})
}
</tbody>
</table>
);
}
}
export default CommentList;
Hope this works for you.

Error : 'list' is not defined no-undef 'route' is not defined no-undef

I am building web application using railway api, on submitting train number I am trying to display data but getting the above error. Actually I used if else condition on fetching data.
below is the code.
import React, { Component } from "react";
export default class TrainRoute extends Component {
constructor(props) {
super(props);
this.state = { trainNumber: "", trainRouteList: "" };
this.onChange = this.onChange.bind(this);
this.onSubmitForm = this.onSubmitForm.bind(this);
}
onChange(e) {
this.setState({ [e.target.id]: e.target.value } );
}
onSubmitForm(e) {
e.preventDefault();
fetch(
`https://api.railwayapi.com/v2/route/train/${
this.state.trainNumber
}/apikey/sch9lj34uy/`
)
.then(res => res.json())
.then(data => {
this.setState({ trainRouteList: data }, () =>
console.log(this.state.trainRouteList)
);
});
this.setState({ trainNumber: "" });
}
render() {
const { trainRouteList } = this.state;
if (!trainRouteList) {
const list = <div>No Trains Details to display</div>;
const route = <div>No Routes to display</div>;
} else {
const list = (
<div>
<table>
<tbody>
<tr>
<td>Train Name :</td>
<td> {trainRouteList.train.name} </td>
</tr>
<tr>
<td>Train Number :</td>
<td> {trainRouteList.train.number} </td>
</tr>
<tr>
<td>Class :</td>
<td>
{trainRouteList.train.classes.map(trainClass => (
<span key={trainClass.code}>{trainClass.code},</span>
))}{" "}
</td>
</tr>
</tbody>
</table>
</div>
);
const route = trainRouteList.route.map(routeInfo => (
<table>
<tbody>
<tr>
<td>Station :</td>
<td> {routeInfo.station.name} </td>
</tr>
<tr>
<td>Departure Time :</td>
<td> {routeInfo.schdep} </td>
</tr>
<tr>
<td>Arrival Time :</td>
<td> {routeInfo.scharr} </td>
</tr>
</tbody>
</table>
));
}
return (
<div>
<div className="container">
<form
onSubmit={this.onSubmitForm}
className="col-md-8 col-md-offset-4"
>
<div className="row">
<div className="col-md-3">
<input
type="number"
className="form-control input-lg"
placeholder="Train Number"
id="trainNumber"
value={this.state.trainNumber}
onChange={this.onChange}
/>
</div>
<div className="col-md-1">
<button type="submit" className="btn btn-warning btn-lg">
Check Route
</button>
</div>
</div>
</form>
</div>
<div className="card card-fluid">
<div className="container">
{list}
<h3>Train Route</h3>
{route}
</div>
</div>
</div>
);
}
}
Getting error at list and route in render method. Can Anyone tell
me why I am getting this error as I tried all possible solution
Its because list and route are block level variable and you are trying to access them outside of block.
Solution is, Define those variables outside then update the value in if and else block, by that way we can access anywhere inside render method. Like this:
render() {
const { trainRouteList } = this.state;
let list, route;
if (!trainRouteList) {
list = <div>No Trains Details to display</div>;
route = <div>No Routes to display</div>;
} else {
list = ....;
route = ....;
}

Categories