I initialized i18n
translation object once in a component ( first component that loads in the app ) . That same object is required In all other components. I don't want to re-initialize it in every component. What's the way around ? Making it available to window scope doesn't help as I need to use it in render()
method.
Please suggest a generic solution for these problem and not i18n specific solution .
Can keep global variables in webpack i.e. in
webpack.config.js
In js module can read like
Hope this will help.
Why don't you try using Context?
You can declare a global context variable in any of the parent components and this variable will be accessible across the component tree by
this.context.varname
. You only have to specifychildContextTypes
andgetChildContext
in the parent component and thereafter you can use/modify this from any component by just specifyingcontextTypes
in the child component.However, please take a note of this as mentioned in docs:
The best way I have found so far is to use React Context but to isolate it inside a high order provider component.
You can use mixins in react https://facebook.github.io/react/docs/reusable-components.html#mixins .
I don't know what they're trying to say with this "React Context" stuff - they're talking Greek, to me, but here's how I did it:
Carrying values between functions, on the same page
In your constructor, bind your setter:
Then declare a function just below your constructor:
When you want to set it, call
this.setSomeVariable("some value");
(You might even be able to get away with
this.state.myProperty = "some value";
)When you want to get it, call
var myProp = this.state.myProperty;
Using
alert(myProp);
should give yousome value
.Extra scaffolding method to carry values across pages/components
You can assign a model to
this
(technicallythis.stores
), so you can then reference it withthis.state
:Save this to a folder called
stores
asyourForm.jsx
.Then you can do this in another page:
If you had set
this.state.someGlobalVariable
in another component using a function like:that you bind in the constructor with:
the value in
propertyTextToAdd
would be displayed inSomePage
using the code shown above.Is not recommended but.... you can use componentWillMount from your app class to add your global variables trough it... a bit like so:
still consider this a hack... but it will get your job done
btw componentWillMount executes once before rendering, see more here: https://reactjs.org/docs/react-component.html#mounting-componentwillmount