Reputation: 1156
Here I'm creating a local variable persons
inside the App
class then assigning a JSX
to it based on some condition and then passing it({persons}
) inside render()
method.
let persons = null;
if (this.state.showPerson) {
persons = (
<div>
<RenderPerson
name={this.state.customers[0].name}
age={this.state.customers[0].age} />
<RenderPerson
name={this.state.agents[1].name}
age={this.state.agents[1].age} />
</div>
);
}
I'm getting a compilation error at let showPersons = null;
. In VS code if I hover over the red marked line of let
keyword it says: [js] Unexpected token. A constructor, method, accessor, or property was expected.
Upvotes: 2
Views: 724
Reputation: 59501
You can do what Carlo suggests in his post. However, you probably don't need the persons
variable at all. So if you don't need that variable elsewhere in your app, consider the following solution:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
showPerson: false
}
}
render() {
return (
{this.state.showPerson && <div>
<RenderPerson
name={this.state.customers[0].name}
age={this.state.customers[0].age}
/>
<RenderPerson
name={this.state.agents[1].name}
age={this.state.agents[1].age}
/>
</div>}
);
}
}
The syntax above is called a short-circuit evaluation:
As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:
false && (anything) is short-circuit evaluated to false.
true || (anything) is short-circuit evaluated to true.
In your app, this means:
this.state.showPerson
is false, then false && JSX = false
, which renders nothing.this.state.showPerson
is true, then true && JSX = true
, which renders your JSX.Alternatively, you can also use a ternary expression:
condition ? expr1 : expr2
If
condition
is true, the operator returns the value ofexpr1
; otherwise, it returns the value ofexpr2
Which in your app would be:
return (
{this.state.showPerson ? <div>
<RenderPerson
name={this.state.customers[0].name}
age={this.state.customers[0].age}
/>
<RenderPerson
name={this.state.agents[1].name}
age={this.state.agents[1].age}
/>
</div> : null}
);
But I personally prefer the former solution.
Upvotes: 4
Reputation: 652
You are probably doing something like this
class App extends React.Component {
// ...
let persons = null;
// ...
}
while you should do
class App extends React.Component {
constructor(props) {
super(props);
this.persons = null;
}
}
See more about the class syntax here https://babeljs.io/learn-es2015/#classes
Upvotes: 0