Meraj
Meraj2y ago

Cannot display table using React

Hi, I am trying to display a simple table but it is showing me error. Been stuck on this for two weeks. Here is my code on codesandbox: https://codesandbox.io/s/angry-gauss-lvsrn3?file=/src/App.js Embedding it here too:
import "./styles.css";

export default function App() {
const products = ["A", "B", "C"];
const counts = [3, 4, 6];

let userArranged = [];
for (let i = 0; i < products.length; i++) {
userArranged[i] = { product: products[i], counts: counts[i] };
}

return (
<div className="cart-table">
<div className="heading-cart">Your cart:</div>
<div className="header-cart">
<div className="table-header-cell">Product</div>
<div className="table-header-cell">Count</div>
</div>
<div className="cart-products">
{userArranged[0].map((productArray) => (
<div className="actual-cart">
{productArray.map((prod) => (
<div className="table-body-cell">{prod}</div>
))}
</div>
))}
</div>
</div>
);
}
import "./styles.css";

export default function App() {
const products = ["A", "B", "C"];
const counts = [3, 4, 6];

let userArranged = [];
for (let i = 0; i < products.length; i++) {
userArranged[i] = { product: products[i], counts: counts[i] };
}

return (
<div className="cart-table">
<div className="heading-cart">Your cart:</div>
<div className="header-cart">
<div className="table-header-cell">Product</div>
<div className="table-header-cell">Count</div>
</div>
<div className="cart-products">
{userArranged[0].map((productArray) => (
<div className="actual-cart">
{productArray.map((prod) => (
<div className="table-body-cell">{prod}</div>
))}
</div>
))}
</div>
</div>
);
}
The error: userArranged[0].map is not a function Can someone help me out please?
CodeSandbox
angry-gauss-lvsrn3 - CodeSandbox
angry-gauss-lvsrn3 using react, react-dom, react-scripts
Solution:
Message Not Public
Sign In & Join Server To View
Jump to solution
4 Replies
aprillion
aprillion2y ago
{ product: products[i], counts: counts[i] } is an Object and non-array objects don't have Array.prototype.map() you are not using counts in the returned value, so no idea what you are trying to achieve to help with a solution ¯\_(ツ)_/¯ for a general advice for debugging, I recommend to log any value that looks suspicious (when you believe it should be something, but the error message sounds like it's something else), e.g. console.log(userArranged[0])
Meraj
Meraj2y ago
Thanks for replying. I just want a table with Products and Counts as two columns with their respective values under them. Products Counts A 3 B 4 C 6 I also tried userArranged.push([products, counts]) to have a different array but it gave me two rows, first one filled with all products and second one with all counts.
Solution
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Meraj
Meraj2y ago
Thank you so much. This did it. Much obliged!