How can I declare globle variable in react?
Ad
I have to declare x variable in render method and use in outer method.
var x = document.getElementById('pick').value
But it error shows that x is not defined.How can i define it other way?thank you.Here is full code
handleSelect(key) {
if(key == 1){
window.location.href = '/portfolio.html?'+x;
}
if(key == 2){
window.location.href = '/transaction.html?'+x;
}
},
render:function() {
return (
<div>
<Tabs activeKey={this.state.key} onSelect={this.handleSelect}>
<Tab eventKey={0} title="home"> </Tab>
<Tab eventKey={1} title="Tab 1">Tab 1 content</Tab>
<Tab eventKey={2} title="Tab 2">Tab 2 content</Tab>
<Tab eventKey={3} title="Tab 3">Tab 3 content</Tab>
</Tabs>
<h1>here is your portfolio list</h1> <br/>
<select id="pick">
{
this.state.data.map(function(data) {
return <option value={data.id}>{data.name}</option>
})
}
</select>
{
if(this.state.data.length > 0)
window.x = document.getElementById('pick').value
}
</div>
);
}
Ad
Answer
Ad
If you are using Common JS based pattern, using module.exports, any vars are by default local. Ignoring that what you are trying to do is not a recommended practice, you should be able to make it work by declaring as -
window.somevar = value;
And use it like -
if (window.someVar){...}
Ad
source: stackoverflow.com
Related Questions
Ad
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad