I have a variable that I need in my React class.
But when I define it in the construtor
, it becomes undefined when I try to use it in the render()
method.
How can I make it so that my variable is available in the render()
method?
Here is what I have:
export default class GameConsole extends React.PureComponent {
constructor(props) {
super(props);
var domainUrl = window.location.origin;
}
render() {
return (
<div>
<GameControl
init={{
masterUrl = domainUrl;
CodePudding user response:
Write this:
export default class GameConsole extends React.PureComponent {
constructor(props) {
super(props);
}
render() {
var domainUrl = window.location.origin;
return (
<div>
<GameControl
init={{
masterUrl = domainUrl;
CodePudding user response:
Assign the value to the component's local state:
constructor() {
super();
this.state = {
domainUrl: window.location.origin,
};
}
render() {
// Can access it on `this.state` inside render
this.state.domainUrl;
}