Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS code in functional presentation component

Still getting to grips with React and ES6. I have the following functional presentation component which works fine:

const Jobs = (props) => (
  <section id="jobs">
    <div>
      {
        props.jobs.map(job =>
          <div className="job" key={job.slug}>
            <p><strong>{job.title} at <Link to={"/jobs/" + job.slug}>{job.company}</Link></strong></p>
            <p>{job.intro}</p>
          </div>
        )
      }
    </div>
  </section>
)

However, when I try to add some extra JS between the brackets as shown below I get errors about unexpected token.

const Jobs = (props) => (
  <section id="jobs">
    <div>
      {
        console.log("THIS DOESN'T WORK")
        props.jobs.map(job =>
          <div className="job" key={job.slug}>
            <p><strong>{job.title} at <Link to={"/jobs/" + job.slug}>{job.company}</Link></strong></p>
            <p>{job.intro}</p>
          </div>
        )
      }
    </div>
  </section>
)

Could someone explain why this doesn't work.

like image 363
tommyd456 Avatar asked Aug 19 '26 05:08

tommyd456


1 Answers

It has to do with what babel is transforming the code into.

return <div>{myValue}</div>;

Becomes

return React.createElement("div", null, myValue);

So having a random console.log in the middle of that, such as

return <div>{
  console.log(myValue);
  myValue
}</div>;

Would become

return React.createElement("div", null, console.log(myvalue); myValue);

Obviously that is no longer valid javascript. Because of this, the only thing that is valid inside a JSX transformation is an expression that evaluates to a single value.


Reading some of the comments on other answers, I see you are actually wanting to do conditional logic inside your JSX.

For this, you have a few options at your disposal.

1. Extract a variable

let conditionalValue = "Loading";

if (condition)
  conditionalValue = myValue;

return <div>{conditionalValue}</div>;

2. Extract a method

return <div>{renderValue()}</div>

...

renderValue() {
  if (condition)
    return myValue;

  return "Loading"
}

3. Use a ternary

return <div>{condition ? myValue : "Loading"}</div>;

4. Exploit boolean evaluation

If you want to show a fallback for something

return <div>{myValue || "Loading"}</div>;

If you want to only show something based on a condition

return <div>{condition && myValue}</div>;

NOTE: all of the above examples are just as valid if you replace myValue with another component, e.g. <p>Hello World</p>.

like image 56
Michael Peyper Avatar answered Aug 21 '26 09:08

Michael Peyper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!