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,
};
You Can Definitely Use Global Variables To Manage Global State 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.
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>
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With