I have a functional component that has been passed data ({clicked}) from its parent function, but when I try to use it as a variable in my function, it errors out. Here is my current code:
function Songs({clicked}) {
const songListFiltered = songList.filter(item => item.{clicked} === true)
const songDisplayed = songListFiltered[Math.floor(Math.random() * songListFiltered.length)]
return (
<div className="song-box">
<img src={songDisplayed.artwork} alt="album artwork" />
<h3>{songDisplayed.songName}</h3>
<p>{songDisplayed.artistName}</p>
</div>
)
}
I need to check if songList has the data in {clicked}, in order to filter those songs from the list, but I'm not sure how to make it work. Would love any help!
Depending on the shape of your data, you would invoke this different ways.
The variable {clicked} would be an object with key value pairs, so you would need to use it as clicked.yourCustomValue. If it's an array, you would use the index, so item.clicked[0], and if clicked is a function, you would need to invoke it with clicked().
Based on the statement
I need to check if songList has the data in {clicked}
And based on the code
songList.filter(item => item.{clicked} === true)
i assume that the variable {clicked} would be an array containing a collection of song objects that have been selected by the user, and the data type of the songList variable is an array containing song objects
So, you can replace the variable songListFiltered with
const songListFiltered = songList.filter(function (e) {
let result = [];
for (let songClicked of clicked) {
if (e.songName === songClicked.songName) {
result.push(e);
}
}
return result.length === 0 ? null : result;
});
Or if you mean {clicked} is a property that you add to the each of songList object when you have selected a song, then you can use typeof when checking the condition filter. Then, the code could be as follows songList.filter(item => typeof(item.clicked) !== "undefined")