I am trying to display array data in a table for my react app. Every time i reference the data in the table cells in returns the same element for all the columns. I would like to display each of the dates in each column.
My Table:
function SomeComponenet(props) {
return (
<React.Fragment>
{props.attendence.map.forEach((attendence, index) => {
return (
<Paper>
<Table aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell align="right">
{attendence.Attendence[index].date}
</TableCell>
<TableCell align="right">
{attendence.Attendence[index].date}
</TableCell>
<TableCell align="right">
{attendence.Attendence[index].date}
</TableCell>
<TableCell align="right">
{attendence.Attendence[index].date}
</TableCell>
<TableCell align="right">
{attendence.Attendence[index].date}
</TableCell>
</TableRow>
</TableHead>
</Table>
</Paper>
);
})}
</React.Fragment>
);
}
My data:
const fakeData = [
{
Name: "A Person",
Attendence: [
{
date: "2019/12/01",
attendence: 1
},
{
date: "2019/12/02",
attendence: 1
},
{
date: "2019/12/03",
attendence: 1
}
]
}
];
you need another map inside the {props.attendence.map}
link to codesandbox https://codesandbox.io/s/sad-grass-sg5hr
import React, { Fragment } from "react";
import { Table } from "reactstrap";
function Test() {
const attendence = [
{
Name: "A Person",
Attendence: [
{
date: "2019/12/01",
attendence: 1
},
{
date: "2019/12/02",
attendence: 1
},
{
date: "2019/12/03",
attendence: 1
}
]
}
];
return (
<Fragment>
{attendence.map(person => {
return (
<Table>
<thead>
<tr>
<th>Name</th>
{person.Attendence.map(personAttendendance => {
return <th>{personAttendendance.date}</th>;
})}
</tr>
</thead>
<tbody>
<tr>
<td>{person.Name}</td>
{person.Attendence.map(personAttendendance => {
return <td>{personAttendendance.attendence}</td>;
})}
</tr>
</tbody>
</Table>
);
})}
</Fragment>
);
}
export default Test;
that's because all the indexes are the same in one iteration of the topper map. you can't use forEach on a map this way.
you can remove forEach and do another map on attendence.Attendence
something like this:
function SomeComponenet(props) {
return (
<React.Fragment>
{props.attendence.map((attendence, index) =>{
{console.log(attendence.Attendence)}
return(
<Paper >
<Table aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
{attendence.Attendence.map( newAttendence => {
return(
<TableCell align="right">
{newAttendence.date}
</TableCell>
)
})}
</TableRow>
</TableHead>
</Table>
</Paper>
);
})}
</ReactFragment>
);
}
Related
I need to achieve something like this in the picture.
I need to create a table with three rows, where the third row is below the first and second rows, and the width of the third row is the combined width of the first and second rows.
CODESANDBOX: CLICK HERE FOR CODESANDBOX
CODE
const CustomTable = () => {
const handleSubmit = () => {};
return (
<TableContainer component={Paper}>
<Formik
initialValues={[
{
id: 1,
attribute: "",
thirdRow: ""
}
]}
onSubmit={handleSubmit}
>
{({ values }) => (
<Form>
<FieldArray
name="rows"
render={(arrayHelpers) => (
<React.Fragment>
<Box>
<Button
variant="contained"
type="submit"
startIcon={<AddIcon />}
onClick={() =>
arrayHelpers.unshift({
id: Date.now(),
attribute: "",
ruleId: "",
thirdRow: ""
})
}
>
Add New
</Button>
</Box>
<Table sx={{ minWidth: 650 }} aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>Attribute</TableCell>
<TableCell>
<span />
Rule ID
</TableCell>
<TableCell colSpan={2}>Third Row</TableCell>
</TableRow>
</TableHead>
<TableBody>
{values.rows?.map((row, index) => (
<CustomTableRow
key={row.id}
row={row}
index={index}
arrayHelpers={arrayHelpers}
/>
))}
</TableBody>
</Table>
</React.Fragment>
)}
/>
</Form>
)}
</Formik>
</TableContainer>
);
};
export default CustomTable;
You could tweak each "row" to really render 2 rows where the second row's column spans 2 column widths.
demo.js
<Table sx={{ minWidth: 650 }} aria-label="simple table">
<TableHead>
<TableRow
sx={{
"th": { border: 0 }
}}
>
<TableCell>Attribute</TableCell>
<TableCell>Rule ID</TableCell>
</TableRow>
<TableRow>
<TableCell colSpan={2}>Third Row</TableCell>
</TableRow>
</TableHead>
<TableBody>
{values.rows?.map((row, index) => (
<CustomTableRow
key={row.id}
row={row}
index={index}
arrayHelpers={arrayHelpers}
/>
))}
</TableBody>
</Table>
CustomTableRow
const CustomTableRow = ({ row, index }) => {
return (
<>
<TableRow
sx={{
"th, td": { border: 0 }
}}
>
<TableCell component="th" scope="row">
<FastField
name={`rows.${index}.attribute`}
component={TextField}
fullWidth
/>
</TableCell>
<TableCell>
<FastField
name={`rows.${index}.ruleId`}
component={TextField}
fullWidth
/>
</TableCell>
</TableRow>
<TableRow>
<TableCell colSpan={2}>
<FastField
name={`rows.${index}.thirdRow`}
component={TextField}
fullWidth
/>
</TableCell>
</TableRow>
</>
);
};
I prefer to use grid layout. You won't then use Table elements but will then want to give the role attribute for accessibility.
The nice thing about using grid layout is that you get a lot of flexibility so you can then say check for [theme.breakpoints.down("md")] and adjust your gridTemplateAreas accordingly.
So, you would do something like the following to get all the 3 rows stacked one over the other.
[theme.breakpoints.down("md")]: {
gridTemplateColumns: "1fr",
gridTemplateAreas: `"upper1"
"upper2"
"bottom"`,
gap: "0px",
}
The other benefit of using gridArea is that the display is visual so it is easy to see as you are designing your layout
I forked your codesanbox and the link and it is at https://codesandbox.io/s/dry-tdd-vv6z1s?file=/demo.js
The complete code is given below.
import React 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";
import { Box, Button } from "#mui/material";
import AddIcon from "#mui/icons-material/Add";
import { FieldArray, Form, Formik } from "formik";
import CustomTableRow from "./CustomTableRow";
import { styled } from "#mui/material/styles";
const Wrapper = styled(Box)(({ theme }) => ({
display: "grid",
gridTemplateColumns: "1fr 1fr",
gridTemplateAreas: `"upper1 upper2 "
"bottom bottom"`,
gap: "0px"
}));
const Upper1 = styled(Box)(({ theme }) => ({
gridArea: "upper1"
}));
const Upper2 = styled(Box)(({ theme }) => ({
gridArea: "upper2"
}));
const Bottom = styled(Box)(({ theme }) => ({
gridArea: "bottom"
}));
const CustomTable = () => {
const handleSubmit = () => {};
return (
<TableContainer component={Paper}>
<Formik
initialValues={[
{
id: 1,
attribute: "",
ruleId: "",
thirdRow: ""
}
]}
onSubmit={handleSubmit}
>
{({ values }) => (
<Form>
<FieldArray
name="rows"
render={(arrayHelpers) => (
<React.Fragment>
<Box>
<Button
variant="contained"
type="submit"
startIcon={<AddIcon />}
onClick={() =>
arrayHelpers.unshift({
id: Date.now(),
attribute: "",
ruleId: "",
thirdRow: ""
})
}
>
Add New
</Button>
</Box>
<Box aria-label="simple table">
<Wrapper>
<Upper1 style={{ border: "2px blue solid" }}>
Attribute
</Upper1>
<Upper2 style={{ border: "2px blue solid" }}>
Rule ID
</Upper2>
<Bottom style={{ border: "2px blue solid" }}>
Third Row
</Bottom>
</Wrapper>
<Box>
{values.rows?.map((row, index) => (
<CustomTableRow
key={row.id}
row={row}
index={index}
arrayHelpers={arrayHelpers}
/>
))}
</Box>
</Box>
</React.Fragment>
)}
/>
</Form>
)}
</Formik>
</TableContainer>
);
};
export default CustomTable;
My goal is to have a table that I can sort by location or activationDate using <select>. Now my sorting is now working but I need to select options(location or activationDate) multiple times for it to reflect in the table. What I need to do to make my sorting reflect asap after I select (eg. sort by location)
my sample obect:
[
{
fullName: "honer Baron",
location: "A building",
activationDate: "2022-07-08 09:30:34"
},
{
fullName: "jett valo",
location: "B building",
activationDate: "2022-07-07 10:30:34"
}
]
const AgentSalesModal = ({ obectsToputInTable, show, hide }) => {
const [sortBy , setSortBy] = useState("");
const tableRow = [];
useEffect(() => {
setTableRow();
}, [sortBy ]);
const setTableRow = () => {
if (sortBy == "location") {
return obectsToputInTable
.sort((a, b) => {
console.log(filterBy);
return a.location - b.location;
})
.map((item, key) => (
<tr key={key}>
<td>{item.location}</td>
<td>
{item.fullName}
</td>
<td>{item.activationDate}</td>
</tr>
));
} else {
return obectsToputInTable
.sort((a, b) => {
var dateA = new Date(a.date).getTime();
var dateB = new Date(b.date).getTime();
return dateA > dateB ? 1 : -1;
})
.map((item, key) => (
<tr key={key}>
<td>{item.location}</td>
<td>{item.subscriberId}</td>
<td>
{item.fullName}
</td>
<td>{item.activationDate}</td>
</tr>
));
}
};
const hideModal = () => {
hide();
setSortBy("");
};
return (
<React.Fragment>
<Modal
show={show}
onHide={hideModal}
size="lg"
aria-labelledby="contained-modal-title-vcenter"
centered>
<Modal.Header>
<Modal.Title id="contained-modal-title-vcenter">
Sales Commission
</Modal.Title>
</Modal.Header>
<Modal.Body className="dateModal text-center">
<div className="overflow">
<form>
<select
className="form-select mb-4"
onChange={(e) => setSortBy(e.target.value)}>
<option value="" disabled defaultValue hidden>
Select Value to sort by
</option>
<option value="location">Sort by Location</option>
<option value="activationDate">Sort by Activation Date</option>
</select>
</form>
<table className="table">
<thead>
<tr>
<th>Location</th>
<th>Subscriber Fullname</th>
<th>Activation Date</th>
</tr>
</thead>
<tbody>{setTableRow()}</tbody>
</table>
</div>
</Modal.Body>
<Modal.Footer>
<Button
onClick={() => {
hide();
setSortBy("");
}}>
Close
</Button>
</Modal.Footer>
</Modal>
</React.Fragment>
);
};```
I would use another state to render the result of setTableRow() eg., rows.
const [rows, setRows] = useState([]);
And set the state in the useEffect with the sortBy dependency.
useEffect(() => {
const tableRows = setTableRow();
setRows(tableRows);
}, [sortBy]);
In your render method:
<tbody>{rows}</tbody>
UPDATE
Ideally in this scenario we want to compare using === instead of == but if you introduce antoher filter option a switch will work better, lets try this instead:
const setTableRow = () => {
// Check the value of sortBy here instead
console.log('sortBy', sortBy);
switch(sortBy) {
case "location":
return obectsToputInTable
.sort((a, b) => {
return a.location - b.location;
})
.map((item, key) => (
<tr key={key}>
<td>{item.location}</td>
<td>
{item.fullName}
</td>
<td>{item.activationDate}</td>
</tr>
));
case "activationDate":
return obectsToputInTable
.sort((a, b) => {
var dateA = new Date(a.date).getTime();
var dateB = new Date(b.date).getTime();
return dateA > dateB ? 1 : -1;
})
.map((item, key) => (
<tr key={key}>
<td>{item.location}</td>
<td>{item.subscriberId}</td>
<td>
{item.fullName}
</td>
<td>{item.activationDate}</td>
</tr>
));
default:
return obectsToputInTable
.map((item, key) => (
<tr key={key}>
<td>{item.location}</td>
<td>{item.subscriberId}</td>
<td>
{item.fullName}
</td>
<td>{item.activationDate}</td>
</tr>
));
}
};
Side note: The key in the map(item, key) function simply returns an index value, you may be better off using item.subscriberId instead but I don't see that value in the sample json.
I have uploaded an image in the images folder of my Node server and the path is stored in the MYSQL database. I want to display the image in my ReactJS application. I am getting the error:
http://127.0.0.1:8080/images/abc.jpg 404 (Not Found)
const baseURL = "http://localhost:8080/data";
export default function Displaydata() {
const [userdata, setuserdata] = React.useState([]);
React.useEffect(() => {
axios.get(baseURL)
.then((response) => {
setuserdata(response.data);
console.log(response.data);
});
}, []);
if (!userdata) return null;
return (
<>
<h2>Data</h2>
<table border="1">
<thead>
<tr>
<th>S.No</th>
<th>userid</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{userdata.map(({ userid, name,image },index) => {
let sno=0;
return (
<tr key={userid}>
<td>{index + 1}</td>
<td>{userid}</td>
<td>{name}</td>
<td><img src={image} alt={image}/></td>
</tr>
);
})}
</tbody>
</table>
</>
);
}
What can I try to fix this?
I have this code :
const HistoricalGrid = ((props) => {
return (
<div className="main-table">
<DataTable rows={props.selectedFile} headers={headers}>
{({ rows, headers, getTableProps, getHeaderProps, getRowProps }) => (
<Table {...getTableProps()}>
<TableHead>
<TableRow>
{headers.map((header) => (
<TableHeader {...getHeaderProps({ header })}>
{header.header}
</TableHeader>
))}
</TableRow>
</TableHead>
<TableBody>
{props.selectedFile.map((row) => (
<TableRow rows="4" {...getRowProps({ row })}>
<TableCell key={row.id} >{row.name}</TableCell>
<TableCell key={row.id}>{row.type}</TableCell>
<TableCell key={row.id}>{new Date().toString()}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</DataTable>
But, I only get the rows data when a button is clicked, how can I keep the rows even if has no value ?
you can check the array length and use a ternary :
{props.selectedFile.length
? props.selectedFile.map((row) => (
...
))
: <TableRow>No result</TableRow>
}
const generateNRows = nb => {
const rows = [];
for($i = 0; $i < $nb; $i++){
rows.push(<tr/>);
}
return rows;
}
const nowDate = new Date();
return (...
{props.selectedFile.map((row) => (
<TableRow {...row} key={row.id} >
<TableCell>{row.name}</TableCell>
<TableCell>{row.type}</TableCell>
<TableCell>{nowDate.toString()}</TableCell>
</TableRow>
))}
{props.selectedFile.length < 4 && (
<>
{generateNRows(4 - props.selectedFile.length)}
</>
)}
I am using React js. I have a class Stock.js where I am fetching an api and displaying the data on the webpage in the form of table.
When I click on the table data (table data are links) It sends the item.symbol to onhandleclick() method. For example:
|Symbol|Age|
|X | 20|
|Y |22 |
So the values in symbol table are referred as item.symbol
Here if I click on X it sends the value X to onhandleclick() and now I want to send this value X or Y whichever user clicks on to another class. By another class I mean let's say I have a class xyz.js I wanna send the value of item.symbol to class xyz.js so I can use this value and do whatever I want with that value in my xyz.js class. Is there a way to do it?
My code: (Stock.js)
import React, { Component } from "react";
import { Link } from "react-router-dom";
import Symbols from "./Symbols";
export default class Stocks extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
isLoaded: false,
symbolsname: "",
};
}
handleClick(symbol) {
//pass the value to another class here
}
componentDidMount(symbol) {
fetch("http://131.181.190.87:3001/all")
.then((res) => res.json())
.then((json) => {
this.setState({
isLoaded: true,
items: json,
});
});
}
render() {
let filteredItems = this.state.items.filter((item) => {
return (
item.symbol.toUpperCase().indexOf(this.state.search.toUpperCase()) !==
-1 || item.industry.indexOf(this.state.search) !== -1
);
});
var { isLoaded, items } = this.state;
if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div>
<table border={2} cellPadding={1}>
<thead>
<tr>
<th>Symbol</th>
<th>Name</th>
<th>Industry</th>
</tr>
</thead>
<tbody>
{filteredItems.map((item) => (
<tr>
<Link to="/symbols">
<td
key={item.symbol}
onClick={() => this.onhandleclick(item.symbol)} //here I am passing the value of item.symbol to onhandleclick()
>
{item.symbol}
</td>
</Link>
<td key={item.name}>{item.name}</td>
<td key={item.industry}>{item.industry}</td>
</tr>
))}
}
</tbody>
</table>
</div>
);
}
}
}
After doing what maniraj-murugansaid in the answers, it says undefined, so I have uploaded the screenshot
You could redirect to symbol.js using history.push with click event handler like, (Remove Link tag here) So change,
<Link to="/symbols">
<td key={item.symbol} onClick={() => this.onhandleclick(item.symbol)} //here I am passing the value of item.symbol to onhandleclick()>
{item.symbol}
</td>
</Link>
to,
<td key={0} onClick={() => this.onhandleclick(item.symbol)}
style={{ cursor: "pointer", color: "blue" }}
>
{item.symbol}
</td>
And onHandleClick function like,
onhandleclick(data) {
const { history } = this.props;
history.push({
pathname: "/Symbol",
symbol: data
});
}
Here the second property is props that you can pass which is symbol in your case so you can give it like, symbol: data ..
Working Sandbox: https://codesandbox.io/s/react-router-v4-withrouter-demo-2luvr
Update:
-> After the update from OP , there are some changes that have been made.
=> import { BrowserRouter } from "react-router-dom"; in the main component index.js where you are initializing the parent component in the call to ReactDOM.render .
index.js:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
const rootElement = document.getElementById("root");
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
rootElement
);
stocks.js:
import React, { Component } from "react";
import { Link } from "react-router-dom";
import Symbols from "./Symbols";
const filteredItems = [
{ symbol: "X", name: "item1", industry: "industry1" },
{ symbol: "Y", name: "item2", industry: "industry2" }
];
export default class Stocks extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
isLoaded: false,
search: "",
symbol: ""
};
}
updateSearch(event) {
this.setState({ search: event.target.value });
}
onhandleclick(data) {
const { history } = this.props;
history.push({
pathname: "/Symbols",
symbol: data
});
}
componentDidMount() {}
render() {
return (
<div>
<form className="form-for-table-search">
Search symbol or industry:
<input
type="text"
value={this.state.search}
onChange={this.updateSearch.bind(this)}
/>
{" "}
<button type="button" className="btn-submit">
Search
</button>
<br />
</form>
<table border={2} cellPadding={1}>
<thead>
<tr>
<th>Symbol</th>
<th>Name</th>
<th>Industry</th>
</tr>
</thead>
<tbody>
{filteredItems.map((item, index) => (
<tr key={index}>
<td
key={0}
onClick={() => this.onhandleclick(item.symbol)} //here I am passing the value of item.symbol to onhandleclick()
style={{ cursor: "pointer", color: "blue" }}
>
{item.symbol}
</td>
<td key={item.name}>{item.name}</td>
<td key={item.industry}>{item.industry}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
Symbols.js:
import React from "react";
export default class Symbol extends React.Component {
componentDidMount() {
console.log("came here", this.props.location.symbol);
}
render() {
return <div>Symbol value: {this.props.location.symbol}</div>;
}
}
Updated Sandbox
You could export a function from Symbol.js and use that in handleClick.
// Symbol.js
export default class Symbol {
doSomething(symbol) {
// do something
}
}
// Stocks.js
import Symbol from 'Symbol.js';
handleClick(symbol) {
Symbol.doSomething(symbol);
};