Wasteland Wasteland - 2 months ago 29
React JSX Question

Reactjs - accessing variables

How can I access variable bvar in the code below? Also, when would I declare variables as:

a) state

b) between constructor() and render()

c) inside render() - my understanding is that I'd set them here if a variable can change and I'd like to set it each time a component renders. So if I know something is not changing at all, it'd be a const and where would I set it?

import React, {Component} from 'react';

export default class App extends Component {
constructor(props) {
super();
// Set the initial grid in
this.state = {
value: 4,
xsquares: 10,
ysquares: 10
};

var bvar = "cat";
}
render() {
var avar = [
"Hydrogen",
"Helium",
"Lithium",
"Beryl­lium"
];

let cvar = "dog";

return (
// Add your component markup and other subcomponent references here.
<div>
<h1>Hello, World! {this.state.value}</h1>
<h2>{this.state.xsquares}</h2>
<h3>{avar[0]}</h3>
<h4>{this.bvar}</h4>
<h3>{cvar}</h3>
</div>

);
}
}


All variables display apart from bvar.

Please advise.

Answer

bvar declared inside your constructor is not accessible inside render() method. It is out of scope. As answered by Caleb, you would need to use instance variable: this.bvar = "cat"

When would I declare variables as:

a) state

Use state if changes in data should affect the view (e.g. store user location in state so that current temperature can be established and rendered based on this location). Also, state can be used in the logic found in other methods of your component (e.g. fetch background image based on user's current location).

b) between constructor() and render()

Variables declared inside other methods of your component are often used to temporarily store data coming, for example, from the state, props, input fields etc. These variables are only accessible within those methods, e.g.

constructor() {
...
}

onInputText() {
    var accountNumber = this.refs.inputField.value;
    this.props.handleInputText(accountNumber);
}

render() {
...
}

c) inside render()

Variables are often declared inside render() to temporarily store data held in state or props. These variables are only accessible inside render(), e.g.

class WelcomeScreen extends React.Component {
    render() {
        var userName = this.props.userName;
        return (
            <div>
                Hello, { userName }!
            </div>
        );
    }
}