Search code examples
javascriptreactjsglobal-variables

Global variable for react


I don't know, how to use a global variable.

I want to make "this.props.topic.text" a global variable to use it on an other app of my project. How can I do that?

export default class Topic extends Component {

  deleteThisTopic() {
    Topics.remove(this.props.topic._id);
  }

  test() {
  
  }
  render() {
    return (

      <Router>
    <div>
      <ul>
        <Link to="/sub"><li onClick={this.test.bind(this)}>{this.props.topic.text}  ARN:  {this.props.topic.arn}</li></Link>
        <Link to="/log"><button onClick={this.test.bind(this)}>S'inscrire</button></Link>
        <Link to="/"><button >Cacher</button></Link>
        <button onClick={this.deleteThisTopic.bind(this)}>Suprimer</button>
      </ul>

      <hr/>
      <Route exact path="/log" component={AppInscription}/>
      <Route exact path="/sub" component={AppSub}/>


    </div>
  </Router>
  );
  }
}

Topic.propTypes = {

  topic: PropTypes.object.isRequired,
};


Solution

  • It is a terrible idea, but probably the best/easiest way to use a global variable in React is to put it on the window. In a component you could do something like window.topicText="some text" and then access it via window.topicText everywhere else.

    Ideally, if you have data, and in your case likely state, that you need to persist from component to component, you should look into something like Redux or Flux. I prefer Redux.