7

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

1 Answer 1

35

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.