0

I am trying to render elements from my state (array) but they don't want render on the screen. If I perform console.log(b.name) it logs my names in console.

renderAllElements() {
    this.state.myData.map(b => {
        return(
            <div>
                <h4>{b.name}</h4>
            </div>
        )
    })
}

render() {
    return (
        <div>
            {this.renderAllElements()}
        </div>
    )
}
2
  • 1
    What is in this.state.myData? Commented Dec 6, 2017 at 10:05
  • 3
    return the map. Commented Dec 6, 2017 at 10:05

3 Answers 3

4

You need to return back your map :

renderAllElements() {
  return this.state.myData.map(b => {
      return(
        <div>
            <h4>{b.name}</h4>
        </div>
     )
  })
}
Sign up to request clarification or add additional context in comments.

2 Comments

Oh yes! I'm so distracted :D
@Mac Guess these mistakes are common with all devs :D
2

You are correctly invoking your renderAllElements() function in your render method. You also seem to correctly map through your array variable, but the function doesn't return anything back to render once finished mapping.

Simply add a return for your map function and it should work:

renderAllElements() {
  return this.state.myData.map(b => {
      return(
        <div>
            <h4>{b.name}</h4>
        </div>
     )
  })
}

One-liner alternative:

renderAllElements() {
  return this.state.myData.map(b => <div><h4>{b.name}</h4></div>);
}

Comments

1

Since you already use array functions you can alternatively rewrite it without curly braces:

renderAllElements = () => (
    this.state.myData.map(b => (
        <div>
            <h4>{b.name}</h4>
        </div>
    ));
)

So you don't need to remember about return statement :)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.