user6247099
user6247099

Reputation:

Try to call a component inside a component - React

So I started with React and I have these two Components.

In the first component I want to iterate an array of objects with the map() function (which works) and call the other component that for now just returns a simple h1 tag.

Well, nothing is been called and there is no error in the console. I believe the problem is in the return sentence in the renderAvatarData() (if I do console.log after the return sentence it seems to not get there but if the console.log is before the return it invokes)

HomePageBoxesData.js

import React, { Component } from 'react';

import AvatarDetails from './AvatarDetails';

class HomePageBoxesData extends Component{

  constructor(props) {
    super(props);   
  };

  renderAvatarData(){
    this.props.data.map(data => {
        return <AvatarDetails data={data}/>     
    });
  }

  render(){
    return(
        <div>
            {this.renderAvatarData()}
        </div>
     );
   }
};

export default HomePageBoxesData;

AvatarDetails.js

import React, { Component } from 'react';

class AvatarDetails extends Component{

    constructor(props) {
      super(props); 
    };

    render(){
       return(
         <h1>Hello World</h1>
       );
    }
};

export default AvatarDetails;

Upvotes: 0

Views: 908

Answers (2)

Elias Ghali
Elias Ghali

Reputation: 853

i agree with Mayank Shukla but i usually use this method in this case:

render() {
        return(
        <div>
        _.map(this.props.data, function(value, key){
          return(
            <AvatarDetails key={key} data={value} />
          )
        })
       </div>

i am not sure if there is one better than the other

Upvotes: 0

Mayank Shukla
Mayank Shukla

Reputation: 104369

Issue is in renderAvatarData() method, you forgot to use return with map, Use this:

renderAvatarData(){
    return this.props.data.map((data)=>{
        return <AvatarDetails data={data}/>

    });
}

Since you just want to return the Component, you can directly write it like this:

renderAvatarData(){
    return this.props.data.map(data => <AvatarDetails data={data} /> );
}

Upvotes: 2

Related Questions