dynamically map values of array - reactjs

I want to dynamically call array values within rather than putting them as val1, .val2, .val3 as shown below.
<table>
<thead>
<tr>
{array_keys
.map((arr) => ( <th>{arr}</th> )
)}
</tr>
</thead>
<tbody>
{array
.map((list, key) =>
<tr key={key}>
<td>{list.val1}</td>
<td>{list.val2}</td>
<td>{list.val3}</td>
</tr>
)}
</tbody>
</table>
Above code works to get array keys in and array values in .
I want to fetch all values dynamically, something like:
<tbody>
{array
.map((list, key) =>
<tr key={key}>
{array_keys
.map((arr) => (
<td>{list.{arr}}</td>
)
)}
</tr>
)}
</tbody>
However {list.{arr}} is not an acceptable code in ReactJs. I need it because my array columns shall change, so I can't map static values and want them fetched dynamically in

Related

How ignore inside map element?

I have been struggling with a problem.
I have multidimensional array and i want to display it to table body.
so i tried to do it with map, however i can't ignore the top of map element, so it displays like nest data.
this is how the multidimensioanl array looks
['2022-05-04', '2022-05-04', '2022-05-04', '2022-05-04', '2022-05-04', '2022-05-04']
['10:11:52', '10:11:52', '10:11:53', '10:11:54', '10:11:55', '10:11:56']
['447', '442', '447', '442', '436', '433']
so i tried to let it looks easy like below.
<tbody>
<tr>
<td>{list[0][0]}</td>
<td>{list[1][0]}</td>
<td>{list[2][0]}</td>
</tr>
<tr>
<td>{list[0][1]}</td>
<td>{list[1][1]}</td>
<td>{list[2][1]}</td>
</tr>
<tr>
<td>{list[0][2]}</td>
<td>{list[1][2]}</td>
<td>{list[2][2]}</td>
</tr>
<tr>
<td>{list[0][3]}</td>
<td>{list[1][3]}</td>
<td>{list[2][3]}</td>
</tr>
<tr>
<td>{list[0][4]}</td>
<td>{list[1][4]}</td>
<td>{list[2][4]}</td>
</tr>
</tbody>
so i tried to use map instead of doing this
const tableData = list.map((data, index) =>
data.map((item, idx) => (
<tr>
<td>{listData[idx]}</td>
</tr>
))
);
return(
<tbody>
{tableData}
</tbody>
)
it doesn't look what i expected.
how can i solve this problem ??
"tr" tag length should be longest
but "td" tag length should be the multidimensioanl array length.
The data, as-is, isn't really suited to .map because you need to iterate over the list[x][y]s, where the x changes, but not the y. Turn the list into a structure where mapping will work first by essentially turning the multidimensional array on its side.
const tableData = list[0].map(
(_, i) => (
<tr>
{
list.map(
listItem => <td>{listItem[i]}</td>
)
}
</tr>
)
);
return (
<tbody>
{tableData}
</tbody>
)

Filtering a table from search word

I have a simple table:
<Table bordered striped>
<thead>
<tr>
<th>Account</th>
<th>Status</th>
<th>Date</th>
<th>Requested By</th>
<th>Approved By</th>
<th></th>
</tr>
</thead>
<tbody>
{accountList?.map((account, index) => (
<tr>
<td>{account.name}</td>
<td>{account.status}</td>
<td>
{account.confirmDate == null
? ""
: moment(account.confirmDate).format("DD-MM-YYYY")}
</td>
<td>{account.requestedBy}</td>
<td>{account.approvedBy}</td>
<td style={{ width: 90 }} className={"text-center"}>
<FontAwesomeIcon
icon={faList}
onClick={() => showAccountModal(account)}
/>{" "}
{/* <FontAwesomeIcon
icon={faCreditCard}
onClick={()=>showBankModal(account)}
/> */}
</td>
</tr>
))}
</tbody>
</Table>
And then i Have a free text search box. I would like to filter all accounts, where name contains the search word. I could fairly easy just have to hooks/variables with the full result in one variable and the filtered in another and then swap between the two. But is there something smarter in REACT? Some kind of filter pipe like Angular? I want to do all filtering client side.
You can use array::filter and filter your state in-line right in the render logic.
({ name }) => !nameFilter || name.includes(nameFilter)
Returns true if the nameFilter is falsey ('', null, undefined, 0) and short-circuit the boolean expression and so will return all elements, otherwise will continue evaluating the expression and process name.includes(nameFilter).
Updated code
accountList?.filter(
({ name }) => !nameFilter || name.includes(nameFilter),
).map((account, index) => (...
If you are looking for an in-box solution use https://react-table.tanstack.com/docs/examples/filtering
But your approach is pretty simple: Store raw data (array) like the source of truth, filtered array store in local state.
Add a handler onChange to input something like this setFilteredData(raw.filter(el => el.name.includes(name)))

unique key prop error even with unique key on table row

I am not sure how to correct this issue. I am using a unique ID but react still isn't happy. I tried to do it on each but then it complains about duplicates.
<table>
<tbody>
{!loading &&
products &&
products.map((product) => (
<>
<tr>
<td key={product._id}>{product.name}</td>
<td>
<span>
<strong>{product.desc}</strong>
</span>
</td>
</tr>
</>
))}
</tbody>
</table>
You must put the key in the upper most component: the Fragment. So instead of <> use <React.Fragment key={...}>
or instead of handling the key by yourself, maybe let React handle it for you. I find it pretty handy:
<table>
<tbody>
{
!loading && products && React.Children.toArray(
products.map((product) => (
<tr>
<td>{product.name}</td>
<td>
<span>
<strong>{product.desc}</strong>
</span>
</td>
</tr>
))
)
}
</tbody>
</table>
so you'll never have to worry about assigning keys anymore!
React.Children.toArray
Returns the children opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down.
Official documentation: https://reactjs.org/docs/react-api.html#reactchildrentoarray

React JS: Only map certain elements of an array within JSX tag, where the elements to map are iterated

I have programatically created the above table in React using, the below code:
tableRenderer() {
let table = <Table striped bordered hover responsive="sm" id='mytable'>
<thead>
<tr>
{this.state.headers.map((header, index) =>
<th key={index}>{header} </th>
)}
</tr>
</thead>
{this.state.timeLabels.map((label, index)=>
<tr key={index}> <td><b>{label} </b></td>
{this.state.table.slice(0,4).map((match, index)=>
<td key={index}>{match.teamA} vs {match.teamB}</td>
)}
</tr> )}
</Table>;
However I'm stuck on the last piece of functionality I need: How can I change the value of the slice of the table array, so on the first run it slices 0->number of pitches, second run number of pitches-> number of pitches+number of pitches... etc.
Do I need to create some sot of function that will iterate a variable every time a row is created?
It would be something along the lines of:
{this.state.timeLabels.map((label, index)=> {
const NO_OF_PITCHES = 4;
let from = NO_OF_PITCHES * index;
let to = NO_OF_PITCHES * (index + 1);
return <tr key={index}>
<td><b>{label}</b></td>
{this.state.table.slice(from,to).map((match, index)=>
<td key={index}>{match.teamA} vs {match.teamB}</td>
)}
</tr>)}
} 
that's assuming the slicing is
0,4...
4,8...
8,12...
etc
also you could lift NO_OF_PITCHES to the parent of the map function because it doesn't have to be recreated on each iteration

How to color specific cells in Table

I have a HTML Table in my ReactJS app and I want to color specific cells or rows there. I have my array in state and want to check differences between neighbor rows and then show this differencies by coloring them on red.
class MainTable extends Component {
constructor(props) {
super(props);
this.state = {
results: []
};
}
render() {
const sorted = _.sortBy(this.state.results, ['ORIGIN', 'DATASTAMP']);
return (
<div>
<div>
<Table hover striped bordered responsive size="sm">
<thead>
<tr>
<th>VERSION</th>
<th>DATE</th>
<th>ORIGIN</th>
</tr>
</thead>
<tbody>
{sorted.map(result =>
<tr>
<td>{result.VERSION}</td>
<td>{result.DATASTAMP}</td>
<td>{result.ORIGIN}</td>
</tr>
)}
</tbody>
</Table>
</div>
</div>
);
}
}
I have no idea how to do something like that. Maybe some idea? Sorry for noobie question, I'm new with ReactJS.
To mark some rows you can:
{sorted.map((result, index) =>
<tr className={`item-${index}`}>
<td>{result.VERSION}</td>
<td>{result.DATASTAMP}</td>
<td>{result.ORIGIN}</td>
</tr>
)}
Basically you first need some criteria on which to mark your element, than you can apply a class or style to it. Helpful is classnames so you could do something like that:
{sorted.map((result, index) =>
<tr className={classnames({
even: index % 2 == 0,
odd: !(index % 2 == 0)
})}>
That would add either even or odd to the classes of the <row>, depending on the index in the list.
I guess there are only two things to remember are:
element styles need to objects like: { backgroundColor: #000 } and
css classes need to be added as »className« property
You can use something like
<tr style={{'background-color': result.color}}>...</tr>
or
<tr style={{'background-color': shouldHighlight[key] ? 'red' : 'white'}}>...</tr>
Obviously in second case you need to findout before function, which table rows should be highlighted and store it in the array.
Also, you need to write your map function in format (result, key) => ... or you need to know id of the result.
You can add a flag in each element of your array to indicate if you need to set the background color of your cell or not.
And then use it like this in your render method :
render() {
const sorted = _.sortBy(this.state.results, ['ORIGIN', 'DATASTAMP']);
return (
<div>
<div>
<Table hover striped bordered responsive size="sm">
<thead>
<tr>
<th>VERSION</th>
<th>DATE</th>
<th>ORIGIN</th>
</tr>
</thead>
<tbody>
{sorted.map(result =>
<tr className={(result.colorFlag ? 'colored-background' : '')}>
<td>{result.VERSION}</td>
<td>{result.DATASTAMP}</td>
<td>{result.ORIGIN}</td>
</tr>
)}
</tbody>
</Table>
</div>
</div>
);
And of course, don't forget to create the CSS class
.colored-background {
background-color: #BADA55;
}

Resources