1

I have an array of objects.

notifications = [
{notification:"this is notification1"},
{notification:"this is notification2"},
{notification:"this is notification3"},
]

Ive been trying to map through the array and create HTML code out of it.

 return (
      <div>
      {notifications.map(function(notificationItem) {
        <a> {notificationItem.notification} </a>
      })}
      </div>
    );

Can somebody please tell me what is the mistake in this?

Thank you!

2 Answers 2

3

From .map you should return value - add return statement to .map., also in this case you should add key property for each element., because child elements should have unique keys., you can read more about reconciliation here

var App = React.createClass({
  render: function() {
    const notifications = this.props.notifications
      .map(function(notificationItem, index) {
        return <a key={index}> {notificationItem.notification} </a>;
      });

    return <div>{ notifications }</div>;
  }
});

var notifications = [
  {notification:"this is notification1"},
  {notification:"this is notification2"},
  {notification:"this is notification3"},
];

ReactDOM.render(
  <App notifications={ notifications } />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>

Sign up to request clarification or add additional context in comments.

Comments

1

I'd also add that if you don't need stateful React, you could also write your component in this style:

const notifications = [
   { notification: "1" },
   { notification: "2" },
   { notification: "3" },
];

const App = function({ notifications }) {
  return (
    <div>
      {
        notifications.map((item, index) => <a key={index}>{item.notification}</a>)
      }
    </div>
  )
}

ReactDOM.render(
   <App notifications={ notifications } />,
   document.getElementById("app")
)

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.