How can I declare globle variable in react?

- 1 answer

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
Ad