简体   繁体   中英

Beginner React : Render Syntax Error

I'm a beginner in React, so this might be a silly error..

I can't seem to get my render function to work..

I'm getting:

Failed to compile
./src/components/VideoPlayer/VideoList.js
Syntax error: Unexpected token (56:10)

  54 |       <ul>
  55 |         { 
> 56 |           return (
     |           ^
  57 |             this.props.loadedVideos.map(
  58 |                 (videos, index) => {
  59 |                 return <li 

And my code looks like this:

I matched my code to a tutorial online, and I don't see any obvious problems with it, but like I said, I'm a beginner so maybe I'm not understanding how JSX and rendering works?

Please let me know why this is throwing errors...

render () {
    // console.log('>> [VideoList.js] Inside render VIDEOS RECIEVED ',this.props.loadedVideos);

    if(!this.props.loadedVideos) return null;


    return( 
      <ul>
        { 
          return {
            this.props.loadedVideos.map(
                (videos, index) => {
                return <li 
                  className="videoItem" 
                  key={videos.id.videoId}>{videos.snippet.title} | {videos.snippet.channelTitle}
                  </li>
                }
            )
          }
        }
      </ul>
    )
  }

You don't need that extra return wrapping the map

return {
         this.props.loadedVideos.map(...
         ... 
}

Just do:

return( 
  <ul>
    { 
        this.props.loadedVideos.map(
            (videos, index) => {
            return <li 
              className="videoItem" 
              key={videos.id.videoId}>{videos.snippet.title} | {videos.snippet.channelTitle}
              </li>
            }
        )          
    }
  </ul>
)

As @Tholle explained in the comment you can use JS expressions in JSX. For an expression you don't need a return. You may need it maybe in a callback function as in your code. But, since you are using an arrow function you don't need curly braces for your function body and return . This should work and slightly clear from your code:

render () {
    // console.log('>> [VideoList.js] Inside render VIDEOS RECIEVED ',this.props.loadedVideos);

    if(!this.props.loadedVideos) return null;

    return( 
      <ul>
        { 
            this.props.loadedVideos.map( videos =>
                    <li 
                       className="videoItem" 
                       key={videos.id.videoId}
                    >
                       {videos.snippet.title} | {videos.snippet.channelTitle}
                    </li> )
        }
      </ul>
    )
  }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM