What's Wrong With Using Functional Components Here?

I eventually found the issue to why my code wasn’t working (I had to use class components), but I’m wondering why I couldn’t use functional ones here. Any thoughts?

Code:

const sounds = [
  {
  key: 'Q',
  tune: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3'
  },
  {
    key: 'W',
    tune: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3'
  },
    {
    key: 'E',
    tune: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-3.mp3'
  },
    {
    key: 'A',
    tune: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-4_1.mp3'
  },
    {
    key: 'S',
    tune: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-6.mp3'
  },
    {
    key: 'D',
    tune: 'https://s3.amazonaws.com/freecodecamp/drums/Dsc_Oh.mp3'
  },
    {
    key: 'Z',
    tune: 'https://s3.amazonaws.com/freecodecamp/drums/Kick_n_Hat.mp3'
  },
    {
    key: 'X',
    tune: 'https://s3.amazonaws.com/freecodecamp/drums/RP4_KICK_1.mp3'
  },
    {
    key: 'C',
    tune: 'https://s3.amazonaws.com/freecodecamp/drums/Cev_H2.mp3'
  }
]

const App = () => {
  <div id='display' className='display'>
     {sounds.map((sound, id) => (
        <Box text={sound.key} key={id}/>
      ))}
  
  </div>
   
} 

const Box = (props) => (
    <div className='box'>
         {this.props.text}
    </div>
)

ReactDOM.render(<App />, document.getElementById('root'))  

The functions you posted don’t return anything.

There should be no reason why you would need to use a class component. There is nothing you can do with a CC that you can’t do with a FC. In fact, most modern React devs don’t use CCs much at all anymore.

One issue is here:

const App = () => {
  <div id='display' className='display'>
     {sounds.map((sound, id) => (
        <Box text={sound.key} key={id}/>
      ))}
  </div>
} 

Notice the curly braces - this component is returning nothing.

The other issue is here:

         {this.props.text}

This is not a CC so props are not passed in to this. They are passed in as a parameter, this variable should be props.text, or:

         {props.text}

When I fix those, I get output to the screen.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.