When calling Object.keys it returns a array of the object's keys.
Object.keys({ test: '', test2: ''}) // ['test', 'test2']
When you call Array#map the function you pass will give you 2 arguments;
- the item in the array,
- the index of the item.
When you want to get the data, you need to use item (or in the example below keyName) instead of i
{Object.keys(subjects).map((keyName, i) => (
<li className="travelcompany-input" key={i}>
<span className="input-label">key: {i} Name: {subjects[keyName]}</span>
</li>
))}
Answer from TryingToImprove on Stack OverflowWhen calling Object.keys it returns a array of the object's keys.
Object.keys({ test: '', test2: ''}) // ['test', 'test2']
When you call Array#map the function you pass will give you 2 arguments;
- the item in the array,
- the index of the item.
When you want to get the data, you need to use item (or in the example below keyName) instead of i
{Object.keys(subjects).map((keyName, i) => (
<li className="travelcompany-input" key={i}>
<span className="input-label">key: {i} Name: {subjects[keyName]}</span>
</li>
))}
You get this error because your variable subjects is an Object not Array, you can use map() only for Array.
In case of mapping object you can do this:
{
Object.keys(subjects).map((item, i) => (
<li className="travelcompany-input" key={i}>
<span className="input-label">{ subjects[item].name }</span>
</li>
))
}
How to render an array of objects with Array.map in React
How to render element in React.js from object map
reactjs - Object.entries.map to render react components array - Stack Overflow
how to render component from .map() in react
How to use map object in React?
-
{users.map(user => (
- {user.name} ))}
How do you map a list of objects in React?
{product.name}
Price: ${product.price}
))} ); }; ``` In this **above example**, each product is rendered with its name and price, showcasing how to effectively map through a list of objects in React.What is an object map?
Hi Everyone,
I have just posted a new article about rendering objects and data in react with Array.prototype.map for beginners.
How to render an array of objects with Array.map in React
Please have a read and let me know about any constructive feedback you might have in order for me to keep improving it.
Thanks!
Your array declaration is wrong. you should use object or array that includes objects. Try this block.
const tabs = {
tab1: {
name: "Tab 1",
renderComponent: () => <Tab1Component />
},
tab2: {
name: "Tab 2",
renderComponent: () => <Tab2Component />
}
};
Also surround your js code with {} like;
const MyComponent= () => {
const activeTab = "tab1";
return <>{tabs[activeTab].renderComponent()}</>;
};
export default MyComponent;
Here things i guess you did wrong is
1) adding the single quotes around the object-key
2) writing key-value pairs in array without enclosing it in {}
I think you should do something like this
const tabs = [
{
tab1: {
name: 'Tab 1',
renderComponent: () => <Tab1Component />
},
tab: {
name: 'Tab 2',
renderComponent: () => <Tab1Component />
}
}
];
const activeTab = 'tab1';
and
const MyComponent = ({tabs}) => {
const activeTab = 'tab1';
return (
<>
// How to render it?
// function invocation?
// createElement??
tabs[0][activeTab].renderComponent();
</>
);
};
From your question, it seems like you are confused when to store values in array and values as object in react state. And it depends on your requirement.
store in array, if data is used only for display purpose and not going to be changed using any event. like, to render dynamic options in select box. You can store values as array and can use 'Array.map' to create component array and render it.
Objects are generally used when you are changing data / update data on events. Objects are handy when it comes to update specific value inside it. like, you are rendering table row with checkbox in first column and on checkbox mark/unmark you need to update related row data property.
If your application requires both things to be achieved, you should do as following,
{
areas: ['areaid_0', 'areaid_1', 'areaid_2'],
areaDetails: {
'areaid_0': {title: 'Some title', isSelected: false},
'areaid_1': {title: 'Some title', isSelected: false},
'areaid_2': {title: 'Some title', isSelected: false}
}
}
When it comes to rendering you can do like,
this.state.areas.map(x => {
const areaDetail = this.state.areaDetails[x];
<Component key={x} {...areaDetail}... />
})
When you wants to update any object, you can do like,
this.state.areaDetails[x].isSelected = true;
Hope, this will be helpful to you.
Storing objects in a sort of "ID map" like this is something that is often recommended by the Redux docs. Note, the keys are the IDs by convention, not an arbitrary attribute like title.
While you can indeed use the Object.entries style that you have demonstrated, you are almost always going to want to have some sort of logical sort order.
You should not rely on JavaScript retaining sort order of keys, and for this reason, libraries like normalizr (which Abramov recommends) that automatically convert to this normalized structure will also return a result array of IDs that will retain sort order. Reference Here
The "Normalizing State Shape" docs from Redux also explicitly recommend you rely on an array of IDs for sort order:
- Any references to individual items should be done by storing the item's ID.
- Arrays of IDs should be used to indicate ordering.
Your state shape might look like this:
{
areas: {1: {id: 1, title: 'some title'}, 2: {id: 2, title: 'other title'}},
areaIds: [1, 2],
}
You would then just iterate like this:
areaIds.map(id => <Component key={id} area={areas[id]} />)
If you truly want to do the Object.entries way, you can use a library like lodash which lets you do simply:
_.map(areas, area => <Component key={area.id} area={area} />)
Gosha Arinich is right, you should return your <li> element.
But, nevertheless, you should get nasty red warning in the browser console in this case
Each child in an array or iterator should have a unique "key" prop.
so, you need to add "key" to your list:
this.state.data.map(function(item, i){
console.log('test');
return <li key={i}>Test</li>
})
or drop the console.log() and do a beautiful oneliner, using es6 arrow functions:
this.state.data.map((item,i) => <li key={i}>Test</li>)
IMPORTANT UPDATE:
The answer above is solving the current problem, but as Sergey mentioned in the comments: using the key depending on the map index is BAD if you want to do some filtering and sorting. In that case use the item.id if id already there, or just generate unique ids for it.
You are not returning. Change to
this.state.data.map(function(item, i){
console.log('test');
return <li>Test</li>;
})