Search code examples
javascriptreactjsstatereact-props

Cannot read properties of undefined react / js


I am learning React and passing props from parent to child etc and I have an issue with a component. In the React dev tools, the props are passed correctly through the chain but when I use the map() method on the array (hardcoded) it returns an error 'Cannot read properties of undefined. The props are correctly printed in the console, and thus I do not understand where this error is coming from.

This is what I did:

  • I created a State in the App component
  • The state is passed to SearchResults => TrackList
  • The last step should be use the map method on the Tracklist component and pass each element of the prop to the Track component => This is where the error is

here the link to github here is the github link to my files, https://github.com/aspnet82/jamming

Thanks for any help


Solution

  • The issue is with your PlayList component. Your TrackList component expect tracks as a prop and you are not passing it in PlayList component.

    TrackList Component

    import React from "react";
    import "./Tracklist.css";
    import Track from '../Track/Track.js';
    
    class TrackList extends React.Component {
      render() {    
        return (
          <div className="Tracklist">
            {
              this.props.tracks.map(track => {
                console.log(track)
                return <Track track={track} key={track.id}/>
              })
            }
          </div>
        )
      }
    }
    
    export default TrackList  ;
    
    

    PlayList component

    import React from "react";
    import "./Playlist.css";
    import Tracklist from '../TrackList/Tracklist.js';
    
    class Playlist extends React.Component {
      render() {
        return (
          <div className="Playlist">
            <input value="New Playlist" />
            <Tracklist tracks={ARRAY_OF_TRACKS} /> // Pass Array of tracks here. 
            <button className="Playlist-save">SAVE TO SPOTIFY</button>
          </div>
        );
      }
    }
    
    export default Playlist;