Hasindu Dahanayake
Hasindu Dahanayake

Reputation: 1491

What is the error of this jsx expression?

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

Answers (5)

n8o
n8o

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

radovix
radovix

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

Tarique Javaid
Tarique Javaid

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

hangindev.com
hangindev.com

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

Jackkobec
Jackkobec

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

Related Questions