Reputation: 359
I try to import an array into my parent component and send that data as props to his child
import Seed from './const/Seed';
export default class ProductList extends React.Component{
render() {
const product = Seed.products[0]
return(
<div>
<Product
id = {product.id}
title = {product.title}
/>
</div>
);
}
}
and i received an error: TypeError: Cannot read property '0' of undefined
maybe i did not format the right way? or is there a way to declare a const on a different file?
export default class Seed extends React.Component{
render(){
const products = [
{
id: 1,
title: 'Yellow Pail',
},
{
id: 2,
title: 'Green Pail',
}
]
return products
}
}
Thank you
Upvotes: 7
Views: 50221
Reputation: 5270
The seed file should be :
export const products = [
{
id: 1,
title: 'Yellow Pail',
},
{
id: 2,
title: 'Green Pail',
},
]
export default {
products,
}
and import them as (and usage as) :
import {products} from './const/Seed';
export default class ProductList extends React.Component{
render() {
const product = products[0]
return(
<div>
<Product
id = {product.id}
title = {product.title}
/>
</div>
);
}
}
render
method is used to render your content on the browser and not for exporting the constants. Please review react/JavaScript once more
Upvotes: 35