user6840964 user6840964 - 11 months ago 32
Javascript Question

How do I render components within a state in react?

I'm learning react and I'm stuck on how to render the birthdays within my this.state. I figured I would use something like:


but that doesn't seem to reach each birthday. My getElementByID is equal to a container which exists on my HTML. Any advice/help would be great!

class App extends React.Component {
constructor(props) {

this.state = {
birthdays: {
'January': [{
name: 'Mike',
date: '1/14/90'
}, {
name: 'Joe',
date: '1/7/92'

March: [{
name: 'Mary',
date: '3/7/88'

render() {
return (

ReactDOM.render(<App />,

Answer Source

Try this:

{ Object.keys(this.state.birthdays).map(this.renderBirthdays) }

And then above your render function create a function called renderBirthdays like this:

renderBirthdays: function(key) {
    return (
         <div key={key} index={key} details={this.state.birthdays[key]}>
              {} - {}
render: function() {
    return (
        <div>{ Object.keys(this.state.birthdays).map(this.renderBirthdays) }</div>

So you can take advantage of javascripts map which will take your object and key them. Then we're going to pass this key into a function called renderBirthdays which will iterate over the item. We need to pass a key and an index into the element, and for ease of use, we can pass a details prop into it equal to the currently selected item it's iterating over. That way we can just use {} etc in the element.