letter Q
letter Q

Reputation: 15385

How to get javascript to work in React component

So I don't seem to be able to get my inner most javascript to compile in the render() of one of my component classes. Do I have my syntax wrong or are we not allowed to have Javascript in the render() return HTML with more Javascript inside?

My error is SearchBarAndResults.jsx: Unexpected token (57:12)

  render() {
    let recievedContracts = this.props.passedContracts.recievedContracts;
    if (!recievedContracts) {
      return (
        <div>
          <h3>'Still waiting for JSON Response'</h3>
        </div>
      );
    } else {       
      const allMemberContractsInfo = this.props.passedContracts.allMemberContractsInfo;
      return (
        <div>
          <h3>'allMemberContractsInfo Have Arrived on the Client Side!'</h3>

          <Button>
            <a href='http://www.adnxs.net/' target="_blank">New Bidder</a>
          </Button>

          {
            if (2 === (3 -1)) { // <============= line 57
              return (<h1>1 does equal 1</h1>);
            } else {
              return (<h1>1 does not equal 1</h1>);
            }
          }
          // other code...

Upvotes: 0

Views: 67

Answers (2)

Horo
Horo

Reputation: 102

You should to rewrite statement as an expression for use it in JSX.

{
  2 === (3 -1)
  ? <h1>1 does equal 1</h1>
  : <h1>1 does not equal 1</h1>;
}

Upvotes: 0

JMM
JMM

Reputation: 26787

You can only embed expressions within JSX, not statements (like if).

You can do one of these:

{
  2 === (3 - 1) ?
  <h1>1 does equal 1</h1> :
  <h1>1 does not equal 1</h1>
}

{function () {
  if (2 === (3 - 1)) {
    return (<h1>1 does equal 1</h1>);
  } else {
    return (<h1>1 does not equal 1</h1>);
  }
}()}

Upvotes: 1

Related Questions