Hi all,
I cannot pass keys and values from object into component. I tried with an array also, but with no luck.
Keys and values are shown in console, but not in table.
What am I doing wrong all the time?
import React, { Fragment } from 'react';
const Test = () => {
const someObject = {
title: 'Intro to css',
title_author: 'Adam',
views: '858',
};
return (
<>
<table className='table-auto'>
<thead>
<tr>
<th className='bg-red-200'>Column1</th>
<th className='bg-red-200'>Column2</th>
</tr>
</thead>
<tbody>
{someObject !== null && (
<Fragment>
{Object.entries(someObject).forEach(([k, v]) => {
console.log(`${k} | ${v === null ? 'null' : v}`); // shown in console, but below is not showing
<tr>
<td>{k}</td>
<td>{v}</td>
</tr>;
})}
</Fragment>
)}
</tbody>
</table>
</>
);
};
export default Test;
Hi, the issue is not in the passing, but rather in the structuring of your <React.Fragment>
If you go into the console, you will see that <Test />
renders an empty <tbody>
, rather than a list of <tr>
with empty <td>
.
I have refactored the code so that the mapping of the object is its own function within <Test />
, hopefully it makes it clearer what’s going on.
https://codepen.io/bill-ye/pen/vYxxYbL?editors=0010
forEach
does not return anything. You should use map
and return the JSX inside the map callback.
Change forEach
to map
.
Return the <tr>
Example code. I didn't change anything else in the code
import React, { Fragment } from "react";
const Test = () => {
const someObject = {
title: "Intro to css",
title_author: "Adam",
views: "858"
};
return (
<>
<table className="table-auto">
<thead>
<tr>
<th className="bg-red-200">Column1</th>
<th className="bg-red-200">Column2</th>
</tr>
</thead>
<tbody>
{someObject !== null && (
<Fragment>
{Object.entries(someObject).map(([k, v]) => {
console.log(`${k} | ${v === null ? "null" : v}`); // shown in console, but below is not showing
return (
<tr>
<td>{k}</td>
<td>{v}</td>
</tr>
);
})}
</Fragment>
)}
</tbody>
</table>
</>
);
};
export default Test;
1 Like
Thank you very much @lasjorg and @MatchaCrisp !!
I will use map function more often in future.
Yeah, map get’s used a lot in React, to turn an array of data into JSX.
1 Like
system
Closed
November 20, 2021, 10:20am
6
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.