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
Since we have a default export, importing anything from that file will provide us with a person object. For imports from the info. js file, we will import from two different constants. Therefore, we use {} to precisely target specific things from that file.
Immutability is embraced in the React ecosystem, so const should be your default choice when you define a variable, though it's not really about immutability, but about assigning variables only once. It shows the intent of not changing (re-assigning) the variable even though its content can be changed.
Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in state. Just like with objects, when you want to update an array stored in state, you need to create a new one (or make a copy of an existing one), and then set state to use the new array.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With