3

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
  • 1,584
  • 4
  • 15
  • 37

3 Answers3

6

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>
rickysy
  • 119
  • 4
  • 10
5

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';

luetkemj
  • 171
  • 7
2

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

dex
  • 21
  • 5