Sometimes, we want to iterate through a hash and return JSX elements for each key with React.
In this article, we’ll look at how to iterate through a hash and return JSX elements for each key with React.
Iterate Through a Hash and Return JSX Elements for Each Key with React
To iterate through a hash and return JSX elements for each key with React, we can use the Object.keys
method to get an array with the object property name strings.
Then we can call map
to map them to the elements we want.
For instance, we can write:
import React from "react";
const obj = {
foo: 1,
bar: 2,
baz: 3
};
export default function App() {
return (
<div>
{Object.keys(obj).map((k) => (
<p key={k}>{k}</p>
))}
</div>
);
}
to get all the keys of obj
with Object.keys
.
Then we call map
with a callback to return p elements with the key name k
as its content.
We should set the key
prop to a unique value so that React can key track of the items.
Therefore, now we get:
foo
bar
baz
on the screen.
Conclusion
To iterate through a hash and return JSX elements for each key with React, we can use the Object.keys
method to get an array with the object property name strings.
Then we can call map
to map them to the elements we want.