-1

Hi I am stuck with this issue, am just getting started with react js. Its the HOME js component when button is clicked I want to show some text ( when flag is true) else it should show nothing.

import React from 'react';

export default class Home extends React.Component{

 constructor(props)
 {
    super(props);
    this.state = {flag: false}
    this.showMe = this.showMe.bind(this);

 }
showMe()
 {
   this.state.flag ? ((<div> show this when flag is true </div>) : null)
 }


render()
{

    return(
        <div>
    <h1>Welcome to the Tornadoes Website {this.state.flag}</h1>
    <button type="button" onClick={this.showMe}>Click me </button>


  </div>);
}

}

Error on console:

16:2:  Parsing error: Unexpected token, expected ":"

  14 |  {
  15 |    this.state.flag ? ((<div> show this when flag is true</div>) : null)
> 16 |  }
     |  ^
  17 |
  18 |
  19 | render()

Rohan
  • 109
  • 2
  • 12
  • You've got unbalanced parentheses which is what the error tells you. It looks like a simple typo. – Emile Bergeron Nov 27 '19 at 01:55
  • Once the typo fixed, the answer you've got is just explaining what's in this other popular question [if-else statement inside jsx: ReactJS](https://stackoverflow.com/q/44046037/1218980) – Emile Bergeron Nov 27 '19 at 02:00

1 Answers1

3

You want the showMe handler to only change state.

the return body of showMe should instead be returned in the render function since you are returning JSX/HTML.

showMe() { 
  this.setState({flag: !this.state.flag})
}

render()
{

    return(
    <div>
      <h1>Welcome to the Tornadoes Website {this.state.flag}</h1>
      <button type="button" onClick={this.showMe}>Click me </button>
      {this.state.flag ? ((<div> show this when flag is true </div>) : null)}

    </div>
   );
}
Anthony Chung
  • 1,467
  • 2
  • 22
  • 44