You can import an array of objects into your React component using the import
statement.
Importing from a Separate File
-
Create a file to store your array of objects. For example,
data.js
:// data.js const data = [ { name: "John Doe", age: 30 }, { name: "Jane Doe", age: 25 }, ]; export default data;
-
Import the array into your React component:
// MyComponent.jsx import data from './data'; function MyComponent() { return ( <div> {data.map((item, index) => ( <p key={index}>Name: {item.name}, Age: {item.age}</p> ))} </div> ); } export default MyComponent;
Importing from a JSON File
-
Create a JSON file to store your data:
// data.json [ { "name": "John Doe", "age": 30 }, { "name": "Jane Doe", "age": 25 } ]
-
Import the JSON file using
fetch
orrequire
:// MyComponent.jsx import React, { useState, useEffect } from 'react'; function MyComponent() { const [data, setData] = useState([]); useEffect(() => { fetch('./data.json') .then(response => response.json()) .then(data => setData(data)); }, []); return ( <div> {data.map((item, index) => ( <p key={index}>Name: {item.name}, Age: {item.age}</p> ))} </div> ); } export default MyComponent;
Using a Static Array
You can also directly define your array of objects within your React component:
// MyComponent.jsx
function MyComponent() {
const data = [
{ name: "John Doe", age: 30 },
{ name: "Jane Doe", age: 25 },
];
return (
<div>
{data.map((item, index) => (
<p key={index}>Name: {item.name}, Age: {item.age}</p>
))}
</div>
);
}
export default MyComponent;
These are the most common ways to import an array of objects into React. Choose the method that best suits your project's structure and data management needs.