Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare strings globally in react native

I have a lot of strings in my react-native application. I see some of strings are being used at multiple places. IMO I do not want to hard code strings in my code as this is not good approach. It may takes ages to change same strings on multiple locations if project go on large scale.

What approaches is to declare strings of react native application. I do android development where it has strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string
        name="string_name"
        >text_string</string>
</resources>

What I am doing in JS files.

<Text style={{ fontSize: 22, textAlign: "center" }}>
  Never forget to stay in touch with the people that matter to you.
</Text>
like image 523
N Sharma Avatar asked Apr 25 '17 06:04

N Sharma


1 Answers

There is no specialized resource manager for strings in React Native like you have in Android. You can have a file with all these constants exported and import them wherever you need. Something along these lines:

**** constants.js

export const NeverForget = 'Never forget to stay in touch with the people that matter to you.';
export const OtherString = 'Welcome to the app';

**** Usage:

import { NeverForget } from 'app/constants';

...
<Text style={{ fontSize: 22, textAlign: "center" }}>
  { NeverForget }
</Text>

**** Or

import * as constants from 'app/constants';

...
<Text style={{ fontSize: 22, textAlign: "center" }}>
  { constants.NeverForget }
</Text>
like image 199
Moti Azu Avatar answered Sep 17 '22 03:09

Moti Azu