How to import and export styles in react native?

11,533

Solution 1

create a new file call 'style.js'

export const customStyle = StyleSheet.create({
   blueblue:{
      color: blue
   }
})

and in your component file

import {customStyle} from './style'

...
<Text style={customStyle.blueblue}>Hi</Text>

Solution 2

Export default const is invalid. If you want text to be a default export you will need to define it and export in separate statements.

const text = StyleSheet.create({...}); export default test;

Also it looks like your import path does not match your actual application structure.

import text from './App/styles';

change to

import text from './styles/text.js';

Solution 3

create this on style.js

    const style = StyleSheet.create({
    p: {
        color: 'blue',
        fontSize: 14
      }
    })

export default style;

and import anywhere you want

like this

import Style from './(path to file)/style'

use style like this

<View style={[Style.p, {
                        padding: 20,
                        backgroundColor: 'grey',
                        justifyContent: 'center',
                        alignContent: 'center'
                    }]}>

if single use

 <View style={Style.p}>

so this may help

Share:
11,533
Ajay Jayendran
Author by

Ajay Jayendran

CTO &amp; Co-Founder at pagelizt Being an Android Developer Fell in Love with Android programming!!

Updated on July 09, 2022

Comments

  • Ajay Jayendran
    Ajay Jayendran almost 2 years

    I am new to react native.I learned the benefits of components, embedding external styles.Now I am trying to use global styles.I'd like to use the same styles of text, button throughout my app.

    Better not to repeat the styles in every component, I'd like to create separate text.js, button.js under styles package to customizing view styles. enter image description here

    Here is my project structure.I want to import text.js into my index.js.

    index.js

    import { AppRegistry } from 'react-native';
    import React, {Component} from 'react';
    import {
      Text
    } from 'react-native';
    import text from './App/styles';
    
    export default class FirstApp extends Component{
        render(){
          return (
            <Text styles={text.p}>Customising React</Text>
          );
        }
    }
    AppRegistry.registerComponent('FirstApp', () => FirstApp);
    

    text.js

    import{
      StyleSheet
    } from 'react-native';
    
    export default const text = StyleSheet.create({
      p: {
        color: 'blue',
        fontSize: 14
      }
    });
    

    Is there any way to import my text.js style into text view in index.js?

  • Ajay Jayendran
    Ajay Jayendran about 6 years
    Still, i am getting the same error.) Unable to resolve module "./style/text.js'
  • luetkemj
    luetkemj about 6 years
    @AjayJayendran updated my answer - export default const is invalid.