Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
36
rated 0 times [  39] [ 3]  / answers: 1 / hits: 30460  / 8 Years ago, thu, august 18, 2016, 12:00:00

So I have a React.js component, and I want to loop through an object I import to add HTML options to it. Here is what I tried, which is both ugly and does not work:



import React from 'react';
import AccountTypes from '../data/AccountType';

const AccountTypeSelect = (props) => {
return (
<select id={props.id} className = {props.classString} style={props.styleObject}>
<option value=nothingSelected defaultValue>--Select--</option>
{
$.each(AccountTypes, function(index) {
<option val={this.id}>this.name</option>
})
}
</select>
);
};

export default AccountTypeSelect;


I received this error in the console from the above code:



invariant.js?4599:38 - Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {id, name, enabled, additionalInfo}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of AccountTypeSelect.



Do I really need to convert each object into an array or wrap it with createFragment to use it? What is the best practice for this case?


More From » reactjs

 Answers
9

Instead of $.each use map:



{AccountTypes.map(function(a) {
return (
<option key={a.id} val={a.id}>{a.name}</option>
);
})}

[#60994] Tuesday, August 16, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryanulyssesb

Total Points: 91
Total Questions: 105
Total Answers: 102

Location: England
Member since Tue, Sep 8, 2020
4 Years ago
ryanulyssesb questions
Sat, Mar 20, 21, 00:00, 3 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
Mon, Mar 9, 20, 00:00, 4 Years ago
Sun, Jul 7, 19, 00:00, 5 Years ago
;