Omar
Omar

Reputation: 3411

how to pass props down using map

I'm trying to understand how to pass props down using the map function. I pass down the fruit type in my renderFruits function and in my Fruits sub-component I render the fruit type. I do not understand what is wrong with this code.

import React, { Component } from 'react';
import { render } from 'react-dom';
import Fruits from'./Fruits';

class App extends Component {
  constructor(props) {
    super(props); 
    this.state = {
      fruits: [
        {
          type:'apple',
        },
        {
          type:'tomato',
        }
      ]
    };
  }
renderFruits = () => {
  const { fruits } = this.state;
    return fruits.map(item =>
      <Fruits
          type={item.type}
       />
        );
  }
  render() { 
    return (
      <div>
          {this.renderFruits}
      </div>
    );
  }
}
render(<App />, document.getElementById('root'));

Fruits component where it should render two divs with the text apple and tomato.

class Fruits extends Component {  
  render() {
    const { type } = this.props;
    return(
      <div>
        {type}
      </div>
    );
  }
}   
export default Fruits;

Upvotes: 1

Views: 9682

Answers (1)

Slawa Eremin
Slawa Eremin

Reputation: 5415

You have two problems in you code
- you should call renderFruits in your render function: this.renderFruits()
- should use "key", when you try to render array

renderFruits = () => {
   const { fruits } = this.state;
   return fruits.map( (item, index) =>
      <Fruits
          key={index}
          type={item.type}
      />
   );
  }
  render() { 
    return (
      <div>
          {this.renderFruits()}
      </div>
    );
  }

Upvotes: 3

Related Questions