Reputation: 1491
Here I am trying to do some sort of conditional rendering ,So I need to have a different output based on the state attribute dailyData value but why can't I use if statement like this ?
compile time error called Parsing error: Unexpected token.
render(){
let lineChart = (
if(!this.state.dailyData){
<h1>Loading</h1>
}
else{
<h1>Output</h1>
}
);
return(<div className={container}>
{lineChart}
</div>
);
}
Upvotes: 0
Views: 75
Reputation: 1943
First of all, it is not a JSX problem but JS syntax error. if
is a statement not an expression so you can't assign it to a variable lineChart
.
So instead:
render(){
let lineChart;
if (!this.state.dailyData) {
lineChart = <h1>Loading</h1>;
} else {
lineChart = <h1>Output</h1>;
}
return(<div className={container}>
{lineChart}
<div>);
}
Here is the difference between statements and expressions
Upvotes: 3
Reputation: 3207
Your logic is good, but the way you wrote it is not correct and contains syntax error. Here are the two ways of how you can achieve what you want.
1st
render() {
let lineChart = null;
if (!this.state.dailyData) {
lineChart = <h1>Loading</h1>;
} else {
lineChart = <h1>Output</h1>;
}
return (
<div className={container}>
{lineChart}
<div>
);
}
2nd
render() {
let lineChart = !this.state.dailyData
? <h1>Loading</h1>
: <h1>Output</h1>
return (
<div className={container}>
{lineChart}
<div>
);
}
Upvotes: 1
Reputation: 11
You should use ternary operator here.
let lineChart = !this.state.dailyData ? <h1>Loading</h1> : <h1>Output</h1>
Also your enclosing div tag should be </div>
instead of <div>
Upvotes: 1
Reputation: 4873
You cannot use if/else
as an expression. Use Conditional (ternary) operator instead.
let lineChart = !this.state.dailyData ? (<h1>Loading</h1>) : (<h1>Output</h1>)
Upvotes: 1
Reputation: 6745
Keep it simple:
renderLineChart = () => {
return !this.state.dailyData ? <h1>Loading</h1> : <h1>Output</h1>;
}
render(){
return(<div className={container}>
{this.renderLineChart()}
</div>);
}
Upvotes: 2