0

I'm new to React. Can someone tell me, why this works:

render() {
        return (
            <div>
                <h1>Hello, React!</h1>
                {this._persons.map( function (p, i) {
                    return <Person name={p.name} age={p.age} />
                })}
            </div>
        )
    }

but this not:

getPersons() {
        this._persons.map(function (p, i) {
            console.log(i);
            return <Person name={p.name} age={p.age} />
        });
    }

    render() {
        return (
            <div>
                <h1>Hello, React!</h1>
                {this.getPersons()}
            </div>
        )
    }

The map function is definalty used because I get the result from the log function, but the Person component will not be rendert.

3 Answers 3

3

You never actually return anything from getPersons. Therefore there is nothing to render. You just need to return the result of your call to map:

getPersons() {
  return this._persons.map(function (p, i) {
    console.log(i);
    return <Person name={p.name} age={p.age} />;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

how should I write it then?
0

You need to return the result of the getPersons function.

Comments

0

Your getPersons() method just returning anything.

getPersons() {
    return this._persons.map(function (p, i) {
        console.log(i);
        return <Person name={p.name} age={p.age} />
    });
}

1 Comment

Thank you, thats it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.