Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import const array React

Tags:

reactjs

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

like image 971
TextError Avatar asked May 01 '18 09:05

TextError


People also ask

What is import {} In React?

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.

Can I use const in React?

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.

How do you store an array in state React?

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.


1 Answers

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

like image 183
Ajay Gaur Avatar answered Sep 22 '22 06:09

Ajay Gaur