2

I have separated styles.js and app.js for a simple app. And I have image resources defined as global constant variables. (For logos and profiles) I tried to add these constant image resources in styles.js as well. But with my current method and syntax, I can't export these constant image resources from styles.js because they are no defined in styles variable wrapper.

styles.js:

 'use strict'

import React, { Component } from 'react';
import {StyleSheet} from 'react-native';

/*
  const background_img= require("../../resource/mybackground.png");
  I tried to define the resource path here
*/

var styles = StyleSheet.create({
   /*Styles Definition*/
});

export default styles

app.js:

'use strict'

import React, { Component } from 'react';
import { AppRegistry, Text, TextInput, View, Image,
TouchableOpacity, Alert} from 'react-native';
import styles from './styles.js';

/*const background= require("../../resource/mybackground.png");*/
// I want to move this part to styles.js


export class LoginScene extends Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <Image
         style={[styles.background, styles.container]}
         source={background} //I want to replace to styles.background_img
         resizeMode="cover"
      ></Image>
      /*Other view definitions*/
    );
  }
}

export default LoginScene

I've indicated where I want to make my change in the above code with comment. If I want to route the source file as what I did above, what should I change in styles.js so that I can export the constant global variables at the same time with styles variable wrapper?

1 Answer 1

9

You can export styles as default, then you can also export another variable which can contain a value or an object.

import React, { Component } from 'react';
import {StyleSheet} from 'react-native';

export const assets = {
  background: require("../../resource/mybackground.png"),
}

var styles = StyleSheet.create({
   /*Styles Definition*/
});

export default styles;

then you can just import the default and the named exports when needed:

import styles, { assets } from './styles.js';
Sign up to request clarification or add additional context in comments.

3 Comments

I see, this works. So it means we can only export json object from other *.js files?
Not exactly, you can export variables, constants, functions, classes, arrays, objects. Just remember that you can use only one export default per file. Check out this guide about es6 modules: exploringjs.com/es6/ch_modules.html
Thanks, this helped me to understand the imporrt of a global variable.

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.