Home > OS >  How to import a class and all its objects from another file in React Native?
How to import a class and all its objects from another file in React Native?

Time:10-05

Let's say we have a file named Car.js in the same directory as App.js in which a class is made with several objects:

    class Car {
     constructor(brand, year) {
      this.brand = brand
      this.year = year
     }
    }
    
    let car_1 = new Car("Ford", 2014);
    let car_2 = new Car("BMW", 2020);

Now how do I import this class and all its objects to the App.js file so that I can for example show a text component that includes things like car_1.brand?

`

CodePudding user response:

export default class Car {
  constructor(brand, year) {
    this.brand = brand
    this.year = year
  }
}
    
let car_1 = new Car("Ford", 2014);
let car_2 = new Car("BMW", 2020);

export { car_1, car_2 }

In App.js you can import it as

import Car, { car_1, car_2 } from "./Car";

Please refer to javascript export reference for more details and explanation.

  • Related