Global variable for react

Hi guys I'm still new to react and i don't know, how to use 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() {

  test() {
  render() {
    return (

        <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>

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


Topic.propTypes = {

  topic: PropTypes.object.isRequired,



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.


You can try this: Declare your global variable before your main component App.js and pass this variable as props down the tree.


var myVar = {}

class MyComponent extends Component {

myVar = new Object();
render() {
   return <div>
                 \\ children
                 <MyLeftBranch myVar={myVar} />
                 <MyRightBranch myVar={myVar} />

export default MyComponent;


class Child extends Component {
     { myVar } = this.props;
     \\use myVar


// Since this.state is global from parent to child components
// This was the easiest solution I've found:

import React, { Component } from "react";
import firebase from "../config";

class App extends Component
 constructor(props) {

     // Set the key to the reference name
     // Assign value to firebase DB collection

     this.state = {
         roomsRef: firebase.firestore().collection("rooms")

// reference it anywhere in the component:

componentDidMount() {


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.