I have a dynamically generated array of list items
const ArtistProfile = props => {
// api data
const tracks = props.data.artistTopTracks && props.data.artistTopTracks.tracks
const [songs, setSongs] = useState(null)
const songRef = useRef(null)
// effect hook that creates list of SongListItem components
useEffect(() => {
if (tracks) {
const trackTags = tracks.map((track, index) => {
if (index > 4) return
return (
<SongListItem ref={songRef} role="button" key={track.id} onClick={() => songRef.current.focus()}>
<SongTag
image={track.album.images[1].url}
duration={msToTime(track.duration_ms)}
name={track.name}
explicit={track.explicit}
/>
</SongListItem>
)
})
setSongs(trackTags)
}
}, [tracks])
return (
<ArtistProfileContainer>
<ul>{songs}</ul>
</ArtistProfileContainer>
)
}
Im trying to use the onClick
event to focus on one item in the list. All my list items are passed this ref const songRef = useRef(null)
and I'm using the songRef.current
property to focus on the element I'm clicking on. This isn't focusing on anything when clicking so none of my styles are changing.
const SongListItem = styled.li`
background-color: #1d1d1d;
:focus {
svg {
opacity: 0.7;
}
background-color: #181818;
}
`
I'm trying to achieve the same results you can see on this Spotify link https://open.spotify.com/artist/5K4W6rqBFWDnAN6FQUkS6x
If you hover over the "Popular" songs you see the styles change temporarily, but once you click it keeps the changes until you click another song.
You just can't focus on li: https://stackoverflow.com/a/30213871/7763883
Add
<li tabIndex="-1" ...
And it will work.
There are tabIndex's in your example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.