'visited array used in array reduce function
In the following code, I wish to declare an array called visited that can record the previously visited {row.name} in the loop delimited by ",", and display it in the second column. My question is how should I insert the code to populate the visited array?
<div className={styles.tbody}>
{rows.map(row => {
return (
<div key={row._id} className={styles.tr}>
<div key={`${row._id}.title`} className={styles.td}>
{row.name} <CompleteSVG/>
</div>
<div key={`${row._id}.status`} className={styles.td}>
{parent} {/* <-- display here */}
</div>
</div>
);
})}
</div>
Solution 1:[1]
You can use a state for this that will hold all of the previously "visited" and then you could display it whichever way you'd like.
Example:
const [visited, setVisited] = useState([]);
const onVisited = rowName => {
setVisited(prev => ([
// Spread previous value to avoid overwriting.
...prev,
rowName,
]));
};
<div className={styles.tbody}>
{rows.map(row => {
return (
<div key={row._id} className={styles.tr}>
<div
onClick={() => onVisited(row.name)}
key={`${row._id}.title`}
className={styles.td}
>
{row.name} <CompleteSVG/>
</div>
<div key={`${row._id}.status`} className={styles.td}>
{parent} {visited.map(t => t)},
</div>
</div>
);
})}
</div>
As for the comma separation, it can just be hardcoded as in the example.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tomleb |
