Pages - Menu

Coding in JSX - How to Comment and if-else statement

Coding in JSX

Dealing with JSX is almost vanilla-html-like but sometimes still a little tricky, so I documented the 2 that I have encountered while I was working with React and JSX.

How to Comment in JSX

I was trying to comment out some of the html inside my jsx and it looked weird and didn't render properly.

render() {
  return (
    <div>
      <div>Hello World<div>
      <!-- This doesn't work! 
        <div>Hidden note</div>
        -->
    <div>
  )
}

What I really needed is this. A 'java' style rather than 'html' style.

render() {
  return (
    <div>
      <div>Hello World<div>
        {/* My Comments...
          <div>Hidden note</div>
          */}>
    <div>
  )
}

if-else in JSX

render() {
  return (
    <div>
      <div>Hello World<div>
      { if true }
        <div>true</div>
      { else }
        <div>false</div>
    <div>
  )
}

A normal if else statement cannot be compiled. However, jsx accepts shorthand notation

render() {
  return (
    <div>
      <div>Hello World<div>
      { true ? <div>true</div> : <div>false</div> }
    <div>
  )
}

No comments:

Post a Comment