Say I have a table that stores items and their weights and I want to sum the total weight from that column and display that at the top on the table. Not using anything other than react/jsx. For more clarification, my table is pulling data stored on a node.js/express server.
I tried writing a function to go into my table component that used reduce, it did not work at all and I'm not sure how to go about it at this point.
Would like the total weight to be displayed next to the table header.
const GearTable = (props) => {
return(
<div style={styles.box}>
<h3>Your Gear Locker</h3>
<br />
<br />
<Table hover style={[styles.font, styles.box]}>
<thead>
<tr>
<th>ID</th>
<th>Item Name</th>
<th>Description</th>
<th>Weight</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
{props.gear.map((gear, id) => {
return(
<tr key={id}>
<th scope="row" style={styles.font}> {gear.id}</th>
<td style={styles.font}> {gear.itemName}</td>
<td style={styles.font}> {gear.description}</td>
<td style={styles.font}> {gear.weight.value}</td>
<td style={styles.font}> {gear.quantity}</td>
<td>
<Button className="btn btn-secondary" size="lg" style={styles.font} id={gear.id} onClick={e => props.update(e, gear)}>Update Locker</Button>
<Button className="btn btn-secondary" size="lg" style={styles.font} id={gear.id} onClick={props.delete}>Delete Item</Button>
</td>
</tr>
)
})
}
</tbody>
</Table>
</div>
);
}
const GearTable = (props) => {
return(
Your Gear Locker
ID
Item Name
Description
Weight
Quantity
{props.gear.map((gear, id) => {
return(
{gear.id}
{gear.itemName}
{gear.description}
{gear.weight.value}
{gear.quantity}
props.update(e, gear)}>Update Locker
Delete Item
)
})
}
);
}
Related
I have a question about the component panel in react
Currently, I have a requirement to create a common component for the Order and Product tables. But the two tables have different numbers of columns, one side has many columns and one side has few columns, besides there are also different table names.
I have a piece of code like this
import React from 'react';
import {Table, Image} from 'react-bootstrap';
import '../Table/index.css';
import Button from '../Button/index';
const TableItem = ({productList}) => {
return(
<Table striped bordered hover>
<thead>
<tr>
<th>No. </th>
<th>Image</th>
<th>Name</th>
<th>Category</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{productList.map((product, index) => (
<tr key={index}>
<td>{product.id}</td>
<td><Image src={product.image} /></td>
<td>{product.name}</td>
<td>{product.category}</td>
<td>{product.price}</td>
<td>
<Button variant="success" onClick={redirectToEdit}>Edit</Button>
<Button variant="danger" onClick={deleteProductItem}>Delete</Button>
</td>
</tr>
))}
</tbody>
</Table>
);
}
export default TableItem;
That code I have created for the product table, but the order table is not because I do not know how to do it properly. I named fixed for the column, I know this is wrong because the order table will also retrieve components from this table, so I can not make the name like that
The order table also has the following columns: Username, address, quantity, status .....
How can I change the code in this component that can be used for both tables
Can anyone help me to explain for this, thank you so much
So you can do something like this, create a table component and pass the columns list and data in there as props that way you can control the table from the parents component and can be used in any way as you want.
const TableItem = ({data, columns}) => {
return(
<Table striped bordered hover>
<thead>
<tr>
{
columns.map((column, index) => {
<th key={ index }>{ column.name }</th>
}
}
</tr>
</thead>
<tbody>
{data.map((product, index) => (
<tr key={index}>
<td>{product.id}</td>
<td><Image src={product.image} /></td>
<td>{product.name}</td>
<td>{product.category}</td>
<td>{product.price}</td>
<td>
<Button variant="success" onClick={redirectToEdit}>Edit</Button>
<Button variant="danger" onClick={deleteProductItem}>Delete</Button>
</td>
</tr>
))}
</tbody>
</Table>
);
}
and in the parent component you can do something like
const parentComponent = () => {
return {
<TableItem columns={ productColumns } data={ productData } />
<TableItem columns={ orderColumns } data={ orderData }
}
}
Note Code not tested and is pseudo
You can pass columns (Array) as a props and render it.
const columns = ['username', 'quantity', 'etc'];
const TableItem = ({List, columns}) => {
return(
<Table striped bordered hover>
<thead>
<tr>
{columns.map((name, index) => (
<th key={index}>{name}</th>
))}
</tr>
</thead>
<tbody>
</Table>
)
})
If you have some common columns then you can pass one more props commonColumns like that.
const TableItem = ({List, columns, commonColumns}) => {
return(
<Table striped bordered hover>
<thead>
<tr>
{commonColumns.map((name, index) => (
<th key={index}>{name}</th>
))}
{columns.map((name, index) => (
<th key={index}>{name}</th>
))}
</tr>
</thead>
<tbody>
</Table>
)
})
Hope this will help you.
I have a dynamic table whose items I render through a list. The idea is that, on clicking the name of a row, a modal will open and that will print certain values retrieved from the backend server.
When I click on a specific person's name, the modal loads for all elements in the table. How do I fix this?
The rendered code for the table is as follows:-
<table className="table">
<thead>
<tr>
<th>S. NO.</th>
<th>NAME</th>
<th>ADDRESS</th>
<th>TELEPHONE</th>
<th>EMAIL</th>
<th>AGE</th>
<th></th>
</tr>
</thead>
<tbody>
{this.state.personData.map((pRow, idx) => (
<>
<PopUp hideModal={this.hideModal} show={this.state.show} id={siteRow.id} />
<tr key={pRow.id}>
<td>{idx + 1}</td>
<td> <a onClick={this.showModal}> {pRow.name} </a> </td>
<td>{pRow.address}</td>
<td>{pRow.phone}</td>
<td>{pRow.email}</td>
<td>{pRow.age}</td>
<td>
{" "}
<DeleteButton id={pRow.id} onDelete={this.onDelete} />{" "}
</td>
</tr>
</>
</tbody>
</table>
In the code for the table, the placement of the PopUp component is such because I want to pass the ID of the particular site to the modal.
This is the rendered code for the modal:-
showModal(e) {
this.setState({
show: true
});
}
hideModal(e) {
this.setState({
show:false
});
this.props.hideModal && this.props.hideModal(e);
}
render() {
if(!this.props.show){
return null;
}
return (
<>
<div>
The ID of the person is: {this.props.id}
<button type="button" className="btn theButton" onClick={this.hideModal}>CLOSE</button>
</div>
</>
);
}
This is very rudimentary code and I haven't added much CSS so this just opens up in the table itself. I want to change this but given the placement of the PopUp component and the fact that I want to pass the ID to the component, I'm not sure how to go about it.
The problem is that you have a series of Popups, but only a variable controlling their visibility. Consider replacing the show state as a simple visibility with a showId one, meant as the "id" of the Popup to be shown.
showModal(id) {
this.setState({
showId: id
});
}
hideModal(e) {
this.setState({
showId: null
});
this.props.hideModal && this.props.hideModal(e);
}
Then:
<table className="table">
<thead>
<tr>
<th>S. NO.</th>
<th>NAME</th>
<th>ADDRESS</th>
<th>TELEPHONE</th>
<th>EMAIL</th>
<th>AGE</th>
<th></th>
</tr>
</thead>
<tbody>
{this.state.personData.map((pRow, idx) => (
<>
<PopUp hideModal={this.hideModal} show={this.state.showId === pRow.id} id={siteRow.id} />
<tr key={pRow.id}>
<td>{idx + 1}</td>
<td> <a onClick={() => this.showModal(pRow.id)}> {pRow.name} </a> </td>
<td>{pRow.address}</td>
<td>{pRow.phone}</td>
<td>{pRow.email}</td>
<td>{pRow.age}</td>
<td>
{" "}
<DeleteButton id={pRow.id} onDelete={this.onDelete} />{" "}
</td>
</tr>
</>
</tbody>
</table>
I did not try the code, but I think it should work.
I am working on a react project I am trying to display data in td, the data is coming from backend and that data is coming in console. But I am not able to display data in table.
For this project I am using functional Component
This is my Child.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
export default function Child() {
const [oldEmployData, newEmployData] = useState([])
async function getEmploysData() {
try {
const response = await axios.get('http://localhost:1000/api/employList');
newEmployData(response.data);
console.log(response.data)
} catch(error) {
console.log(error)
}
}
useEffect(() => {
getEmploysData()
}, [])
return (
<div className='container'>
<div className='row'>
<div className='col-12'>
<table className="table table-bordered">
<thead>
<tr>
<th>Employ Name</th>
<th>Employ Age</th>
<th>Employ Stream</th>
<th>Employ Address</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<button className='btn btn-primary'>Edit</button>
</td>
<td>
<button className='btn btn-danger'>Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
)
}
If I am clear please put a comment
Assuming your axios request is responding with a valid JSON array, you can render that data directly into your table via Array#map() by extending your render logic as shown below:
<tbody>
{data.map(item =>
<tr key={item.id}>
{/* assuming each item in JSON array has firstName, lastName, email
and password fields */}
<td>{item.firstName}</td>
<td>{item.lastName}</td>
<td>{item.email}</td>
<td>{item.password}</td>
{/* suppose you have editItem() and deleteItem() defined, these
can be invoked (during click event) for each item like this */}
<td>
<button className="btn btn-primary"
onClick={() => editItem(item)}>Edit</button>
</td>
<td>
<button className="btn btn-danger"
onClick={() => deleteItem(item)}>Delete</button>
</td>
</tr>)}
</tbody>
An important point to note is that each <tr> element being mapped must have a key prop supplied with a value that is unique to the item being rendered/mapped. With that in mind, the assumption being made above is that each item in the data array has a unique id.
Suppose json data like this
let data = [
{id:1,name:'One'},
{id:2,name:'Two'},
{id:3,name:'Three'}
]
Iterate like this
{data.map(d=>
<tr key={d.id}>
<td>{d.name}</td>
<td>{}</td>
<td>{}</td>
<td></td>
<td><button className='btn btn-primary' onClick={()=>handleEdit(d.id)>Edit</button></td>
<td><button className='btn btn-danger' onClick={()=>handleDelete(d.id)}>Delete</button></td>
</tr>
)}
I am trying to render a table inside a react component but having trouble aligning the rows with the header
render() {
console.log("Top Searches",this.props.topSearches)
return(
<div className="topsearches">
<table border="2" align="center">
<th> Search Term </th>
<th>Count </th>
{this.props.topSearches.map((top_search, index) => (
<tr>
{Object.keys(top_search).map(function(key) {
return <div>
<tbody>
<td align="center">{key} </td>
<td align="right">{top_search[key]}</td>
</tbody>
</div>
})}
</tr>
))}
</table>
</div>
)
}
This is the output i am getting
I assume, you are trying to achieve something like this.
I have edited this in codesandbox here.
https://codesandbox.io/s/sparkling-sound-yd1ih
return (
<div className="topsearches">
<table border="2" align="center">
<thead>
<th> Search Term </th>
<th>Count </th>
</thead>
<tbody>
{props.topSearches.map((top_search, index) =>
Object.keys(top_search).map((key, index) => {
return (
<tr>
<td>{key}</td>
<td>{top_search[key]}</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
);
Modification I made to achieve this:
Added <thead>
Corrected <tbody> loop
Please let me know if you have any further questions!
I have table so I want to retrieve key/value of specific row in which button was clicked.
componentDidMount() {
let com = this;
firebase
.database()
.ref()
.child("bills")
.once("value", snap => {
let items = [];
snap.forEach(childD => {
items.push({
balance: childD.val().balance,
bill_num: childD.val().bill_num,
date: childD.val().date,
key: childD.val().key,
name: childD.val().name,
total: childD.val().total
});
});
Array.prototype.push.apply(com.state.products, items);
com.setState({
products: com.state.products
});
});
}
open = e => {
e.preventDefault();
console.log("kal" + this.state.value);
};
handleChange=event=>{
this.setState({value: event.target.value});
}
render() {
return (
<table className="table table-striped">
<thead>
<tr>
<th scope="col">Bill number</th>
<th scope="col">Name</th>
<th scope="col">Date</th>
<th scope="col">Total</th>
<th scope="col">Balance</th>
<th scope="col">Delete</th>
<th scope="col">Open bill</th>
</tr>
</thead>
<tbody>
{console.log(this.state.products)}
{this.state.products.map((value, key) => (
<tr key={value.key}>
<th scope="row">{value.bill_num}</th>
<td>{value.name}</td>
<td>{value.date}</td>
<td>{value.total}</td>
<td>{value.balance}</td>
<td>
<form onSubmit={this.returnOrder}>
<input value={value.key} type="hidden" />
<button className="btn btn-danger" type="submit">
Return
</button>
</form>
</td>
<td>
<form onSubmit={this.open}>
<input value={value.key} onChange={this.handleChange} ref={ eKey => (this.inputeKey = eKey)} />
<button className="btn btn-info" type="submit">
Open
</button>
</form>
</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<Printout
keya={{
key: this.props.keyas
}}
/>
)}
);
}
}
Typically, tables in React are made from several components: whole table, row and for example buttons in row. So in table you place array of rows. Each row has it's child buttons. So you can send props to RowButtons child with information about clicked row.