score:74
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 specify childcontexttypes
and getchildcontext
in the parent component and thereafter you can use/modify this from any component by just specifying contexttypes
in the child component.
however, please take a note of this as mentioned in docs:
just as global variables are best avoided when writing clear code, you should avoid using context in most cases. in particular, think twice before using it to "save typing" and using it instead of passing explicit props.
score:-7
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:
this.setsomevariable = this.setsomevariable.bind(this);
then declare a function just below your constructor:
setsomevariable(propertytexttoadd) {
this.setstate({
myproperty: propertytexttoadd
});
}
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 you some value
.
extra scaffolding method to carry values across pages/components
you can assign a model to this
(technically this.stores
), so you can then reference it with this.state
:
import reflux from 'reflux'
import actions from '~/actions/actions'
class yourform extends reflux.store
{
constructor()
{
super();
this.state = {
someglobalvariable: '',
};
this.listenables = actions;
this.basestate = {
someglobalvariable: '',
};
}
onupdatefields(name, value) {
this.setstate({
[name]: value,
});
}
onresetfields() {
this.setstate({
someglobalvariable: '',
});
}
}
const reqformdata = new yourform
export default reqformdata
save this to a folder called stores
as yourform.jsx
.
then you can do this in another page:
import react from 'react'
import reflux from 'reflux'
import {form} from 'reactstrap'
import yourform from '~/stores/yourform.jsx'
reflux.definereact(react)
class somepage extends reflux.component {
constructor(props) {
super(props);
this.state = {
somelocalvariable: '',
}
this.stores = [
yourform,
]
}
render() {
const myvar = this.state.someglobalvariable;
return (
<form>
<div>{myvar}</div>
</form>
)
}
}
export default somepage
if you had set this.state.someglobalvariable
in another component using a function like:
setsomevariable(propertytexttoadd) {
this.setstate({
myglobalvariable: propertytexttoadd
});
}
that you bind in the constructor with:
this.setsomevariable = this.setsomevariable.bind(this);
the value in propertytexttoadd
would be displayed in somepage
using the code shown above.
score:-1
globalthis may be supported in some browsers.
you can refer following links
https://webpack.js.org/plugins/provide-plugin/
https://webpack.js.org/plugins/define-plugin/
score:0
for only declaring something, try this. make sure myobj
is assigned at the proper time for you want to access it in render()
, many ways was published before this thread. maybe one of the simplest ways if undefined then create it
does the job.
declare global {
interface window {
myobj: any;
}
}
score:0
create a file :
import react from "react";
const appcontext = {};
export default appcontext;
then in app.js, update the value
import appcontext from './appcontext';
appcontext.username = uname.value;
now if you want the username to be used in another screen:
import appcontext from './appcontext';
appcontext.username to be used for accessing it.
score:1
maybe it's using a sledge-hammer to crack a nut, but using environment variables (with dotenv https://www.npmjs.com/package/dotenv) you can also provide values throughout your react app. and that without any overhead code where they are used.
i came here because i found that some of the variables defined in my env files where static throughout the different envs, so i searched for a way to move them out of the env files. but honestly i don't like any of the alternatives i found here. i don't want to set up and use a context everytime i need those values.
i am not experienced when it comes to environments, so please, if there is a downside to this approach, let me know.
score:5
the best way i have found so far is to use react context but to isolate it inside a high order provider component.
score:8
can keep global variables in webpack i.e. in webpack.config.js
externals: {
'config': json.stringify({ global_variable: "global var value" })
}
in js module can read like
var config = require('config')
var global_variable = config.global_variable
hope this will help.
score:8
here is a modern approach, using globalthis
, we took for our react native app.
globalthis
is now included in...
- modern browsers - mdn documentation
- typescript 3.4 - handbook documentation
- eslint v7 - release notes
appglobals.ts
// define our parent property accessible via globalthis. also apply the typescript type.
var app: globalappvariables;
// define the child properties and their types.
type globalappvariables = {
messagelimit: number;
// more can go here.
};
// set the values.
globalthis.app = {
messagelimit: 10,
// more can go here.
};
// freeze so these can only be defined in this file.
object.freeze(globalthis.app);
app.tsx (our main entry point file)
import './appglobals'
// other code
anywhereelseintheapp.tsx
const chatgroupquery = usequery(get_chat_group_with_messages_by_id, {
variables: {
chatgroupid,
currentuserid: me.id,
messagelimit: globalthis.app.messagelimit, // 👈 used here.
},
});
score:32
create a file named "config.js" in ./src folder with this content:
module.exports = global.config = {
i18n: {
welcome: {
en: "welcome",
fa: "خوش آمدید"
}
// rest of your translation object
}
// other global config variables you wish
};
in your main file "index.js" put this line:
import './config';
everywhere you need your object use this:
global.config.i18n.welcome.en
score:36
is not recommended but.... you can use componentwillmount from your app class to add your global variables trough it... a bit like so:
componentwillmount: function () {
window.myvars = {
ajax: require('../helpers/ajax.jsx'),
utils: require('../helpers/utils.jsx')
};
}
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
score:116
beyond react
you might not be aware that an import is global already. if you export an object (singleton) it is then globally accessible as an import statement and it can also be modified globally.
if you want to initialize something globally but ensure its only modified once, you can use this singleton approach that initially has modifiable properties but then you can use object.freeze
after its first use to ensure its immutable in your init scenario.
const myinitobject = {}
export default myinitobject
then in your init method referencing it:
import myinitobject from './myinitobject'
myinitobject.someprop = 'i am about to get cold'
object.freeze(myinitobject)
the myinitobject
will still be global as it can be referenced anywhere as an import but will remain frozen and throw if anyone attempts to modify it.
example of react state using singleton
https://codesandbox.io/s/adoring-architecture-ru3vt (see usercontext.tsx)
if using react-create-app
(what i was looking for actually) in this scenario you can also initialize global objects cleanly when referencing environment variables.
creating a .env file at the root of your project with prefixed react_app_
variables inside does quite nicely. you can reference within your js and jsx process.env.react_app_some_var
as you need and it's immutable by design.
this avoids having to set window.myvar = %react_app_my_var%
in html.
see more useful details about this from facebook directly:
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
Source: stackoverflow.com
Related Query
- How to declare a global variable in React?
- How to declare global variables in React JS
- How to declare a global variable and access it in all the other modules in ReactJS?
- How to set a state Array from a global variable in React
- How do I declare a generic React component in a const variable from a higher-order component?
- How to declare a variable for inner function in react component?
- How to implement global variable in react functional components
- react - declare global variable inside of a react component
- How to access a Global variable in React JS functional component?
- How to observe change in a global Set variable in useEffect inside react component function?
- How to declare variable inside react function?
- How do I declare and reassign a variable in React Class Component to store a setTimeout reference?
- How to declare a variable before assign it in React using Typescript without "Index signature is missing in type" Error
- How to apply global styles with CSS modules in a react app?
- Where to declare variable in react js
- How do you reference a process.env variable in HTML <script src="" ? React
- Global Variable / Constant in React Native
- How to declare defaultProps on a React component class using TypeScript?
- How to declare default props in react functional component
- How to pass a state className variable to another component in react
- How can I pass a variable from 'outside' to a react app?
- How to set environment variable in React JS..?
- Does React Native have global scope? If not, how can I mimic it?
- How to add global loading/spin effect in axios interceptor for a React project
- How to inject port and host using ENV variable in Create React App Proxy settings?
- How can I get a variable from the path in react router?
- How to import scss file as variable in react with typescript
- How to pass in an instance variable from a React component to its HOC?
- How to append element to variable to be render in react
- How do I insert a Django template variable into a React script?
More Query from same tag
- react-router-dom v6 rendering new page over current page
- stopPropagation does not work in a hierarchy of components
- Why isn't the state of Root component changing?
- Code showing error of expected assignment or functional call
- type of custom object in typescript
- Why display: flex hide my image in Reactjs
- Create search box in the list in react js component
- Access to instance of fullCalendar v5
- Express API backend receiving requests but not responding, Nginx
- Minimum nodejs server setup needed for React using react-router and browserHistory
- React use ref to scroll to a specific component when click on link
- Passing down use state values gives undefined
- How to setup Router link in Reactjs
- React Router routes not working on nginx create-react-app
- ReactCSSTransitionGroup: Elements on their way out stay mounted along with newly mounted elements for a short time
- SVG as a ReactComponent- Is it possible to get width in render
- React Need help Syncfusion data grid
- React passing two functions as a call backs to this.setState
- Unusual error when running create-react-app in terminal on Mac
- styled-components: extend styles and change element type
- React ref to functional component without hooks?
- how to open link from pwa(in android shell) to another browser
- Function overloading with typescript on a react component?
- Material-UI injectFirst doesn't work with storybook
- React, Firebase: Access values of JSON and also get key value
- React 15.4.2 Cannot read property 'ref' of null
- Dynamic import not working in netlify (reactjs)
- Proper way of passing asynchronous data in nextjs to pages
- Animate SVG along path with Framer Motion
- Submitting via button click from different component