Reputation: 2476
I am creating a list of items by using the map
function:
render() {
var accounts = this.props.accounts.map((account, index) =>
<li className="list-group-item" key={index}>{account[0]}<br />
<button type="button" >Go to Login</button>
<button type="button" >Log out</button>
</li>
);
return (
{accounts && (
<ul className="accounts-list list-group">{accounts}</ul>
)}
)
}
This works fine because accounts is an Array.
I need to do the same thing with an Object:
{
"offer": [
"id",
"price-input"
],
"offer_message": [
"id",
"msg-textarea"
]
}
Code:
forms = Object.entries(this.props.forms).forEach(([key, value]) =>
<div className="form-group">
{value}
</div>
)
return (
{forms}
)
This yields no result. In fact, forms
is undefined. How do I go about rendering a list from an object?
Thanks
Upvotes: 2
Views: 57
Reputation: 112917
You are using forEach
which returns undefined
. You want to use map
instead.
Also make sure that you wrap {forms}
in an element and that you give each child in the array a key
prop.
Example
class App extends React.Component {
render() {
const forms = Object.entries(this.props.forms).map(([key, values]) =>
<div className="form-group" key={key}>
{values.join(", ")}
</div>
);
return <div>{forms}</div>;
}
}
ReactDOM.render(
<App
forms={{
offer: ["id", "price-input"],
offer_message: ["id", "msg-textarea"]
}}
/>,
document.getElementById("root")
);
<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="root"></div>
Upvotes: 2
Reputation: 85643
Multiline code should be wrapped in a parentheses. Otherwise, it will return undefined
as you noticed:
=>
(
<div className="form-group">
{value}
</div>
)
Upvotes: 1