Passing Arguments to Event Handlers - reactjs

I'd be grateful if you could help me with my problem.
I've written a component to demonstrate the information of an array which includes both index.js and TableData.js files.Transferring the information of array from index.js to TableData in order to demonstrating them.
I passed the arguments to event handler correctly but I get an error. What's the problem with my code? In which part have I made a mistake?
App.js
import React, {Component, Fragment} from 'react';
import {TableData} from './Layouts'
class App extends Component {
state = {
productList: [
{id: 11, name: 'CD', price: '2000', describe: 'Educational'},
{id: 24, name: 'Pen', price: '3500', describe: 'Design'},
{id: 83, name: 'Pencil', price: '2500', describe: 'Design'}
],
};
handleDeleteByIndex = index => {
const product = this.state.productList;
product.splice(index, 1);
this.setState({productList: product});
};
render() {
const {productList} = this.state;
return (
<Fragment>
<TableData rows={productList} onDeleteRow={this.handleDeleteByIndex}/>
</Fragment>
);
}
}
export default App
TableData.js
import React from 'react';
import {makeStyles} from '#material-ui/core/styles';
import {
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Paper
} from '#material-ui/core';
//****** Style CSS ******
const useStyles = makeStyles({
root: {
width: '100%',
overflowX: 'auto'
},
table: {
minWidth: 650
}
});
const test = 'right';
const TableData= (props) => {
const classes = useStyles();
return (
<Paper className={classes.root}>
<Table className={classes.table} aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>Name Product</TableCell>
<TableCell align="right">Price</TableCell>
<TableCell align="right">Describe</TableCell>
</TableRow>
</TableHead>
<TableBody>
{props.rows.map((item, index) => (
<TableRow key={item.id}>
<TableCell component="th" scope="row">
{item.name}
</TableCell>
<TableCell align={test} data={item.name}>{item.price}</TableCell>
<TableCell align="right">{item.describe}</TableCell>
<TableCell align="right">
<button onClick={() => props.handleDeleteByIndex(index)}>
DEL
</button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
);
};
export default TableData

You are calling a function that does not exist. The passed down function in props is called onDeleteRow, not handleDeleteByIndex.
Just change it into:
onClick={() => props.onDeleteRow(index)}

Related

MUI table Row collapse squashed into one cell when expanded and alignment error

Trying to use MUI table with Collapse to expand/collapse rows. However when using collapse, the the expanded rows are squashed into one cell. How can I align the expanded cells to the parent table cells in a material-ui table?
what i tried is on this link https://codesandbox.io/s/affectionate-leaf-lhb47z
CODE
import React, { useState } from "react";
import { makeStyles } from "#material-ui/core/styles";
import Grid from "#material-ui/core/Grid";
import Card from "#material-ui/core/Card";
import CardHeader from "#material-ui/core/CardHeader";
import Table from "#material-ui/core/Table";
import TableBody from "#material-ui/core/TableBody";
import TableCell from "#material-ui/core/TableCell";
import TableHead from "#material-ui/core/TableHead";
import TableRow from "#material-ui/core/TableRow";
import Paper from "#material-ui/core/Paper";
import TableContainer from "#material-ui/core/TableContainer";
import IconButton from "#material-ui/core/IconButton";
import KeyboardArrowDownIcon from "#material-ui/icons/KeyboardArrowDown";
import KeyboardArrowUpIcon from "#material-ui/icons/KeyboardArrowUp";
const useStyles = makeStyles((theme) => ({
header: {
backgroundColor: "white",
color: "#546e7a",
justifyContent: "left",
padding: "10px 0px",
fontWeight: "bold"
},
content: {
padding: 0
},
status: {
marginRight: "5px"
},
actions: {
justifyContent: "flex-end"
},
summaryTable: {
width: "auto",
marginBottom: "10px",
pointerEvents: "none"
},
noBorder: {
border: "none"
},
denseCell: {
padding: "5px"
},
formControl: {
margin: theme.spacing(1),
minWidth: 120
},
inputGroup: {
marginBottom: theme.spacing(1)
}
}));
const data1 = [
{
amount: 400.0,
dr_cr: "dr",
ledgerName: "Furniture"
},
{
amount: 10,
dr_cr: "dr",
ledgerName: "chocolate"
},
{
amount: 100.0,
dr_cr: "dr",
ledgerName: "goods purchase"
}
];
const data = [
{
amount: 510.0,
dr_cr: "dr",
ledgerName: "Assets"
},
{
amount: 5,
dr_cr: "cr",
ledgerName: "Liability"
}
];
const ExpandableTableRow = ({ children, expandComponent, ...otherProps }) => {
const [isExpanded, setIsExpanded] = React.useState(false);
return (
<>
<TableRow {...otherProps}>
<TableCell padding="checkbox">
<IconButton onClick={() => setIsExpanded(!isExpanded)}>
{isExpanded ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
</IconButton>
</TableCell>
{children}
</TableRow>
{isExpanded && (
<TableRow>
<TableCell/>
{expandComponent}
</TableRow>
)}
</>
);
};
export default function App() {
const classes = useStyles();
const [records, setRecords] = useState(data || []);
const [records1, setRecords1] = useState(data1 || []);
return (
<div className="App">
<Grid item lg={12} md={12} xs={12}>
<Card>
<CardHeader
className={classes.header}
title={"Report"}
classes={{
title: classes.header
}}
/>
<Table stickyHeader>
<TableHead>
<TableRow>
<TableCell />
<TableCell>LedgerName</TableCell>
<TableCell>Debit</TableCell>
<TableCell>Credit</TableCell>
</TableRow>
</TableHead>
<TableBody>
{records.map((item) => (
<ExpandableTableRow
key={item.ledgerName}
expandComponent={
<Table>
<TableBody>
{records1.map((i) => (
<TableRow>
<TableCell>{i.ledgerName}</TableCell>
<TableCell>
{i.dr_cr === "dr" ? Math.round(i.amount, 2) : 0}
</TableCell>
<TableCell>
{i.dr_cr === "cr" ? Math.round(i.amount, 2) : 0}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
}
>
<TableCell>{item.ledgerName}</TableCell>
<TableCell>
{item.dr_cr === "dr" ? Math.round(item.amount, 2) : 0}
</TableCell>
<TableCell>
{item.dr_cr === "cr" ? Math.round(item.amount, 2) : 0}
</TableCell>
</ExpandableTableRow>
))}
</TableBody>
</Table>
</Card>
</Grid>
</div>
);
}

Cannot get data into a material ui collapsible table with react. What am I doing wrong?

Code runs and I get the table but I'm also retreiving some database data. I threw a couple console.logs in the there and my query runs and returns data. However, it doesn't show up in the collapsible table. Appreciate any advice!
import React, { useContext, useState } from "react";
import PropTypes from 'prop-types';
import { useQuery, useMutation } from "#apollo/react-hooks";
import { makeStyles } from '#material-ui/core/styles';
import Box from '#material-ui/core/Box';
import Collapse from '#material-ui/core/Collapse';
import IconButton from '#material-ui/core/IconButton';
import Table from '#material-ui/core/Table';
import TableBody from '#material-ui/core/TableBody';
import TableCell from '#material-ui/core/TableCell';
import TableContainer from '#material-ui/core/TableContainer';
import TableHead from '#material-ui/core/TableHead';
import TableRow from '#material-ui/core/TableRow';
import Typography from '#material-ui/core/Typography';
import Paper from '#material-ui/core/Paper';
import KeyboardArrowDownIcon from '#material-ui/icons/KeyboardArrowDown';
import KeyboardArrowUpIcon from '#material-ui/icons/KeyboardArrowUp';
import CreateTicket from "views/Dashboard/CreateTicket";
import {
LIST_CREATIVE_FORM,
SUBMIT_CREATIVE_FORM,
COMPLETE_CREATIVE_FORM
} from "queries/formSubmission";
import { READ_ME } from "queries/users";
import { Context } from "redux/store";
export default function Tickets() {
const [state, dispatch] = useContext(Context);
const [selectedCreative, setSelectedCreative] = useState(null);
const customer_id = state.customers?.selected?.id;
const { data: me } = useQuery(READ_ME);
let { loading, data, refetch } = useQuery(LIST_CREATIVE_FORM, {
skip: !customer_id,
variables: { customerId: customer_id }
});
const [completeCreativeForm, { loading: completing }] = useMutation(COMPLETE_CREATIVE_FORM, {
skip: !customer_id,
onCompleted: () => {
refetch();
}
});
data = data?.listCreativeForm || [];
console.log(data);
const editable = me?.readMe?.user_level === "master" || me?.readMe?.user_level === "master";
const columns = [
{
Header: "Creative or Promotion Name",
accessor: "creative_promotion_name"
},
{
Header: "Creative Messaging",
accessor: "creative_message"
},
{
Header: "Start Date",
accessor: "creative_start"
},
{
Header: "End Date",
accessor: "creative_end"
},
{
Header: "Landing Page",
accessor: "landing_page"
},
{
Header: "Notes",
accessor: "notes"
},
{
Header: "BanerAds",
accessor: "bannerads",
Cell: ({ original }) => original?.bannerads ? "Yes" : "No"
},
{
Header: "SocialAds",
accessor: "socialads",
Cell: ({ original }) => original?.socialads ? "Yes" : "No"
},
{
Header: "OnlineVideo",
accessor: "onlinevideo",
Cell: ({ original }) => original?.onlinevideo ? "Yes" : "No"
},
{
Header: "Out of Home",
accessor: "out_of_home",
Cell: ({ original }) => original?.out_of_home ? "Yes" : "No"
},
{
Header: "Link to Asset",
accessor: "link_to_assets",
Cell: ({ original }) => (
<a href={original?.link_to_assets} target="_blank">
{original?.link_to_assets ? "View" : ""}
</a>
)
},
{
Header: "Submitted By",
accessor: "submitted_by",
Cell: ({ original }) => (
<div>{original?.user_submitted ? `${original.user_submitted?.first_name} ${original.user_submitted?.last_name}` : ""}</div>
)
},
{
Header: "Completed",
accessor: "completed",
Cell: ({ original }) => original?.completed
? <div style={{ color: "green" }}>Yes</div>
: <div style={{ color: "red" }}>No</div>
},
{
Header: "Completed By",
accessor: "completed_by",
Cell: ({ original }) => (
<>
<div>{original?.user_completed ? `${original.user_completed?.first_name} ${original.user_completed?.last_name}` : ""}</div>
{editable && !original?.completed && (
<a
href="#"
onClick={(e) => {
e.preventDefault();
completeCreativeForm({
variables: {
id: original?.id
}
});
}}
>
Complete
</a>
)}
</>
)
},
{
Header: "",
accessor: "update",
Cell: ({ original }) => (
editable && !original?.completed && (
<a
href="#"
onClick={(e) => {
e.preventDefault();
setSelectedCreative(original);
}}
>
Update
</a>
)
)
}
];
Tickets.propTypes = {
offline: PropTypes.bool
};
const useRowStyles = makeStyles({
root: {
'& > *': {
borderBottom: 'unset',
},
},
});
function Row(props) {
const { row } = props;
const [open, setOpen] = React.useState(false);
const classes = useRowStyles();
console.log("data");
console.log(data);
return (
<React.Fragment>
<TableRow className={classes.root} columns={columns} data={data}>
<TableCell>
<IconButton aria-label="expand row" size="small" onClick={() => setOpen(!open)}>
{open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
</IconButton>
</TableCell>
<TableCell align="right">{data.values.creative_promotion_name} lhey</TableCell>
<TableCell align="right">{data.values.creative_message}</TableCell>
<TableCell align="right">{data.values.creative_start}</TableCell>
<TableCell align="right">{data.values.creative_end}</TableCell>
</TableRow>
<TableRow>
<TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={6}>
<Collapse in={open} timeout="auto" unmountOnExit>
<Box margin={1}>
<Typography variant="h6" gutterBottom component="div">
History
</Typography>
<Table size="small" aria-label="purchases">
<TableHead>
<TableRow>
<TableCell>Date</TableCell>
<TableCell>Customer</TableCell>
<TableCell align="right">Amount</TableCell>
<TableCell align="right">Total price ($)</TableCell>
</TableRow>
</TableHead>
{/*<TableBody>
{row.history.map((historyRow) => (
<TableRow key={historyRow.date}>
<TableCell component="th" scope="row">
{historyRow.date}
</TableCell>
<TableCell>{historyRow.customerId}</TableCell>
<TableCell align="right">{historyRow.amount}</TableCell>
<TableCell align="right">
{Math.round(historyRow.amount * row.price * 100) / 100}
</TableCell>
</TableRow>
))}
</TableBody>*/}
</Table>
</Box>
</Collapse>
</TableCell>
</TableRow>
</React.Fragment>
);
}
console.log(columns)
return (
<TableContainer component={Paper}>
<Table aria-label="collapsible table" columns={columns} data={data}>
<TableBody>
{data.map((row) => (
<Row key={row.id} row={row} />
))}
</TableBody>
</Table>
</TableContainer>
);
}
Ok so here's what code worked for me to pass my database data to the collapsible table...
function Row(props) {
const { row } = props;
const [open, setOpen] = React.useState(false);
const classes = useRowStyles();
return (
<React.Fragment>
<TableRow>
<TableCell>
<IconButton aria-label="expand row" size="small" onClick={() => setOpen(!open)}>
{open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
</IconButton>
</TableCell>
<TableCell align="right">{row.creative_promotion_name}</TableCell>
<TableCell align="right">{row.creative_message}</TableCell>
<TableCell align="right">{row.creative_start}</TableCell>
<TableCell align="right">{row.creative_end}</TableCell>
<TableCell align="right">{row.out_of_home}</TableCell>
<TableCell align="right">{row.link_to_assets}</TableCell>
<TableCell align="right">{row.submitted_by}</TableCell>
<TableCell align="right">{row.completed}</TableCell>
<TableCell align="right">{row.completed_by}</TableCell>
<TableCell align="right">{row.update}</TableCell>
</TableRow>
<TableRow>
<TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={4}>
<Collapse in={open} timeout="auto" unmountOnExit>
<Box margin={1}>
<Table size="small" aria-label="purchases">
<TableRow>
<TableCell>Notes:</TableCell>
<TableCell align="left">{row.notes}</TableCell>
</TableRow>
<TableRow>
<TableCell>Created Time:</TableCell>
<TableCell align="left">{row.created_time}
</TableCell>
</TableRow>
</Table>
</Box>
</Collapse>
</TableCell>
</TableRow>
</React.Fragment>
);
}
const classes = useRowStyles();
return (
<div>
<TableContainer component={Paper} style={{overflowY: "auto", maxWidth: "100%", maxHeight: "600px"}}>
<h2 className={classes.pageHeader}>Tickets</h2>
<Table stickyHeader aria-label="collapsible table" columns={columns} data={data}>
<TableHead>
<TableRow>
<TableCell />
{columns.map((data) => (
<TableCell>{data.Header}</TableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{data.map((datarow) => (
<Row data={datarow.id} row={datarow} />
))}
</TableBody>
</Table>
</TableContainer>
</div>
);
}

React map() data not displaying

The data does not appear in the table in the view. Importing data from db was confirmed with the console.enter image description here
If it is simply used as list.map(), an error saying that it is not a function occurs. So list && list.length > 0 ? I am using list.map((e).
Or do I have to modify the const [list, setList] = useState code part?
import React, { useEffect, useState } from "react";
import axios from 'axios';
import Navbar from './Navbar';
import Box from '#mui/material/Box';
import Button from '#mui/material/Button';
import Table from '#mui/material/Table';
import TableBody from '#mui/material/TableBody';
import TableCell from '#mui/material/TableCell';
import TableContainer from '#mui/material/TableContainer';
import TableHead from '#mui/material/TableHead';
import TableRow from '#mui/material/TableRow';
import Paper from '#mui/material/Paper';
export default function Community() {
const [list, setList] = useState([{
inputData: {
post_id: '',
title: '',
writer: ''
},
}]);
useEffect(() => {
axios.get('http://localhost:5000/post/community').then((res) => {
console.log("성공");
console.log(res.data);
setList(res.data);
})
}, [])
return (
<div>
<Navbar />
<Box>
<Button sx={{ fontWeight: 'bold' }} href="/newpost">게시글 등록</Button>
</Box>
<TableContainer component={Paper}>
<Table aria-label="simple table">
<TableHead>
<TableRow>
<TableCell sx={{ fontWeight: 'bold' }}>Post_id</TableCell>
<TableCell sx={{ fontWeight: 'bold' }}>Title</TableCell>
<TableCell sx={{ fontWeight: 'bold' }} align="right">Writer</TableCell>
</TableRow>
</TableHead>
{list && list.length > 0 ? list.map((e) => {
return (
<TableBody>
<TableRow key={e.post_id}>
<TableCell component="th" scope="row">{e.post_id}</TableCell>
<TableCell align="right">{e.title}</TableCell>
<TableCell align="right">{e.writer}</TableCell>
</TableRow>
</TableBody>
)
}) : ""}
</Table>
</TableContainer>
</div>
);
}
Your first state is set up wrong which is then causing the map not to update the state data. It will only mutate not update.
Change
const [list, setList] = useState([{
inputData: {
post_id: '',
title: '',
writer: ''
},
}]);
To this
const [list, setList] = useState([])

Reading a txt file and put the data in table + calculate

I'm very new to React and I'm playing around with file uploading and reading the values.
I currently have an app where I want to upload a file (the file has different content every time, but the header info stays the same) and format the content, put it into a table and calculate some results.
The txt file contains several rows with information about cable types (Mx) and the length of cable necessary.
I'm trying to
isolate the content to get only rows with 'mx' content
split the content, so I can separate types of cable and lengths
calculate the cumulative length of all cables
There are 4 types (I think) and the format is unfortunately like this
2xM14+1xM10 225.67 0.00 0.00
The first part is types of cables and multiple needed (2xM14 means I have to double the lengths for the results)
The second part is length for each cable (if I have 2xM14 and 1xM10 I need 2xM14225.67 and 1xM10225.67)
The rest is not relevant.
import { Box, Button, TextField } from '#mui/material';
import React, { Component } from 'react';
import { useState, useEffect } from 'react';
import Table from '#mui/material/Table';
import TableBody from '#mui/material/TableBody';
import TableCell from '#mui/material/TableCell';
import TableContainer from '#mui/material/TableContainer';
import TableHead from '#mui/material/TableHead';
import TableRow from '#mui/material/TableRow';
import Paper from '#mui/material/Paper';
export default function Cable() {
const [text, setText] = useState('čekám na soubor');
const [lines, setLines] = useState([]);
const [newLines, setNewLines] = useState([]);
const [results, setResults] = useState(
[{ letters: [], numbers: [] }]
);
const typy = ['M7', 'M10', 'M14', 'M16'];
const [types, setTypes] = useState('');
const showFile = (e) => {
e.preventDefault();
const reader = new FileReader();
reader.onload = (e) => {
const text = e.target.result;
setText(text); // inserts doc
setLines(text.split('\n')) // split text into rows
console.log(lines);
};
reader.readAsText(e.target.files[0]);
};
// selects rows containing 'xM'
const splitLines = (e) => {
setLines(lines.filter(line => line.includes('xM')))
console.log(lines)
}
const splitArr = () => {
const result = lines.reduce((a, c) => {
const [letters, numbers] = c.split(/[ ]+/);
a.push({ letters, numbers });
return a;
}, []);
setResults(() => [...result]);
// setTypes((result.letters).replace(/[x||+]/g, ' '))
console.log(results);
// console.log(types);
};
return (
<Box>
<input type="file" onChange={showFile} />
<TextField
label='gde soubor?'
variant='outlined'
value={text}
fullWidth
disabled
multiline
rows={12}
>{types}</TextField>
<Button onClick={splitLines}>Rozděl do typů - Mx</Button> <br />
<Button onClick={splitArr}>Vlož do tabulky - a vyber délku</Button> <br />
<TableContainer component={Paper} sx={{ minWidth: 650, marginBottom: 5, marginTop: 5}}>
<Table sx={{ minWidth: 650}} aria-label="simple table">
<TableHead>
<TableRow >
<TableCell>Typ</TableCell>
<TableCell>Délka</TableCell>
</TableRow>
</TableHead>
<TableBody >
{results.map((radky, index) => (
<TableRow key={index}>
<TableCell component="th" scope="row" sx={{ fontSize: 11, background: '#eeeeee' }}>
{radky.letters}
</TableCell>
<TableCell component="th" scope="row" sx={{ fontSize: 11, background: '#eeeeee' }}>
{radky.numbers.length > 0 && parseFloat(radky.numbers)}
</TableCell>
<TableCell component="th" scope="row" sx={{ fontSize: 11, background: '#eeeeee' }}>
{radky.letters.length > 0 && radky.letters.replace(/[x||+]/g, ' ')}
</TableCell>
<TableCell component="th" scope="row" sx={{ fontSize: 11, background: '#eeeeee' }}>
{radky.letters.length > 0 && radky.letters.replace(/[x||+]/g, ' ').split(' ') }
</TableCell>
<TableCell component="th" scope="row" sx={{ fontSize: 11, background: '#eeeeee' }}>
{radky.letters.length > 0 && radky.letters.replace(/'M10'/g, '*')}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</Box>
);
}
I also replicated the app on stackblitz(https://stackblitz.com/edit/react-f3zts7)
I'm not sure what should be the ideal way how to do this, any help would be greatly appreciated.

How to display state object elements in another component?

i'm trying to use a table from MaterialUI and populate it with financial data (using promise API). I have three components:
Gl.js
myTable
index.js
I want to use the state object in the Gl.js component and populate the table in myTable.js but not sure how to. Please ask for more details if necessary, I must complete this project.
GL.js
import React, { Component, createContext, Provider } from 'react';
import ReactDOM from 'react-dom';
import axios from "axios";
import CollapsibleTable from './myTable';
export const CTX = React.createContext();
class Gl extends React.Component {
_isMounted = false;
constructor(props) {
super(props)
this.state = {
applBs: []
}
}
getData() {
const axios = require("axios");
axios({
"method": "GET",
"url": "https://fmpcloud.p.rapidapi.com/balance-sheet-statement/AAPL",
"headers": {
"content-type": "application/octet-stream",
"x-rapidapi-host": "fmpcloud.p.rapidapi.com",
"x-rapidapi-key": "4560d76562msh36c4de0a03c6e54p1bf4a2jsne2d882693304",
"useQueryString": true
}, "params": {
"period": "annual",
"apikey": "demo"
}
})
.then(response => {
if (this._isMounted) {
this.setState({ applBs: response.data[0] })
}
})
.catch(error => {
console.log(error)
})
}
componentDidMount() {
this._isMounted = true;
this.getData();
}
componentWillUnamount() {
this._isMounted = false;
}
render() {
return (
<div>
<CollapsibleTable callData={this.state.applBs} />
<CTX.Provider value={ this.state.applBs }>
{this.props.children}
</CTX.Provider>
</div>
)
}
}
ReactDOM.render(<Gl />, document.getElementById("root"))
export default Gl
myTable.js
import React, { Component, Consumer } from 'react';
import ReactDOM from "react-dom"
import PropTypes from 'prop-types';
import { makeStyles } from '#material-ui/core/styles';
import Box from '#material-ui/core/Box';
import Collapse from '#material-ui/core/Collapse';
import IconButton from '#material-ui/core/IconButton';
import Table from '#material-ui/core/Table';
import TableBody from '#material-ui/core/TableBody';
import TableCell from '#material-ui/core/TableCell';
import TableContainer from '#material-ui/core/TableContainer';
import TableHead from '#material-ui/core/TableHead';
import TableRow from '#material-ui/core/TableRow';
import Typography from '#material-ui/core/Typography';
import Paper from '#material-ui/core/Paper';
import KeyboardArrowDownIcon from '#material-ui/icons/KeyboardArrowDown';
import KeyboardArrowUpIcon from '#material-ui/icons/KeyboardArrowUp';
import CTX from "./GL.js"
const useRowStyles = makeStyles({
root: {
'& > *': {
borderBottom: 'unset',
},
},
});
function createData(name, calories, fat, carbs, protein, price) {
return {
name,
calories,
fat,
carbs,
protein,
price,
history: [
{ lineItem: 'Pop', date: '2020-01-05', customerId: '11091700', amount: 3 },
{ lineItem: 'Pop', date: '2020-01-02', customerId: 'Anonymous', amount: 1 },
],
};
}
function Row(props) {
const { row } = props;
const [open, setOpen] = React.useState(false);
const classes = useRowStyles();
return (
<React.Fragment>
<TableRow className={classes.root}>
<TableCell>
<IconButton aria-label="expand row" size="small" onClick={() => setOpen(!open)}>
{open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
</IconButton>
</TableCell>
<TableCell component="th" scope="row">
{row.name}
</TableCell>
<TableCell align="right">{row.calories}</TableCell>
<TableCell align="right">{row.fat}</TableCell>
<TableCell align="right">{row.carbs}</TableCell>
<TableCell align="right">{row.protein}</TableCell>
</TableRow>
<TableRow>
<TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={6}>
<Collapse in={open} timeout="auto" unmountOnExit>
<Box margin={1}>
<Typography variant="h6" gutterBottom component="div">
History
</Typography>
<Table size="small" aria-label="purchases">
<TableHead>
<TableRow>
<TableCell>
Line Item
</TableCell>
<TableCell>
Google
</TableCell>
<TableCell>
Customer
</TableCell>
<TableCell align="right">
Amount
</TableCell>
<TableCell align="right">
Total price ($)
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{row.history.map((historyRow) => (
<TableRow key={historyRow.date}>
<TableCell component="th" scope="row">
{historyRow.date}
</TableCell>
<TableCell>{historyRow.customerId}</TableCell>
<TableCell align="right">{historyRow.amount}</TableCell>
<TableCell align="right">
{Math.round(historyRow.amount * row.price * 100) / 100}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
</Collapse>
</TableCell>
</TableRow>
</React.Fragment>
);
}
Row.propTypes = {
row: PropTypes.shape({
calories: PropTypes.number.isRequired,
carbs: PropTypes.number.isRequired,
fat: PropTypes.number.isRequired,
history: PropTypes.arrayOf(
PropTypes.shape({
amount: PropTypes.number.isRequired,
customerId: PropTypes.string.isRequired,
date: PropTypes.string.isRequired,
}),
).isRequired,
name: PropTypes.string.isRequired,
price: PropTypes.number.isRequired,
protein: PropTypes.number.isRequired,
}).isRequired,
};
const rows = [
createData('Frozen yoghurt', 159, 6.0, 24, 4.0, 3.99),
createData('Ice cream sandwich', 237, 9.0, 37, 4.3, 4.99),
createData('Eclair', 262, 16.0, 24, 6.0, 3.79),
createData('Cupcake', 305, 3.7, 67, 4.3, 2.5),
createData('Gingerbread', 356, 16.0, 49, 3.9, 1.5),
];
export default function CollapsibleTable() {
return (
<TableContainer component={Paper}>
<Table aria-label="collapsible table">
<TableHead>
<TableRow>
<TableCell />
<TableCell>
Apple.Inc
</TableCell>
<TableCell align="right">Calories</TableCell>
<TableCell align="right">Fat (g)</TableCell>
<TableCell align="right">Carbs (g)</TableCell>
<TableCell align="right">Protein (g)</TableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.map((row) => (
<Row key={row.name} row={row} />
))}
</TableBody>
</Table>
</TableContainer>
);
}
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Gl from './GL';
import CollapsibleTable from './myTable';
ReactDOM.render(
<React.StrictMode>
<Gl >
<CollapsibleTable />
</Gl>
</React.StrictMode>,
document.getElementById('root'));
ok then this must be the issue be clear with class and functional component this keyword can be used only in class component!!
check this link for further reference link
in your case have a console in
<TableContainer component={Paper}>
{console.log('callData', props.callData)}
<Table aria-label="collapsible table">
you will get the value of callData use that to display in table

Resources