Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,
};
like image 487
alpheonix Avatar asked Jul 13 '17 12:07

alpheonix


People also ask

Can I use global variables in React?

You Can Definitely Use Global Variables To Manage Global State In React.

How do I set a global variable in React?

One way to declare a global variable in React is to attach a new variable as the property of the window object. For example, create a window.name variable in the index. js file like this: import React from "react"; import ReactDOM from "react-dom"; import App from "./App"; window.name = "John"; const root = ReactDOM.

What is global variable in React JS?

A JavaScript global variable is declared outside the function or declared with window object. It can be accessed from any function. Let's see the simple example of global variable in JavaScript. <script>

Is there a global state in React?

Role of the global state. In React, originally, the state is held and modified within the same React component . In most applications, different components may need to access and update the same state. This is achieved by introducing the global states in your app.


1 Answers

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.

like image 164
Gregg Avatar answered Oct 08 '22 18:10

Gregg