0

Due to react's nature i have to use the ternary operator to output some code. I am getting a parse error because i have JS code as well as html in the output. How can i insert both the JS and html in this ternary statement?

JS

<div>
{
props.starring? "..some code"
: 
    (
    const starrarr = JSON.parse("["+props.starring+"]") //this line is giving me an error
    <div className="altactorimg">
       <h6><img src="#" alt="pictures"/>{starrarr[0]}</h6>
       <h6><img src="#" alt="pictures"/>{starrarr[1]}</h6>
       <h6><img src="#" alt="pictures"/>{starrarr[2]}</h6>
    </div>
    )
}
</div>

I attempted many things like wrapping them inside brackets, and adding JSON.parse directly inside each element but still get errors.

Note: the above code is react jsx

Uriel
  • 195
  • 1
  • 2
  • 14

2 Answers2

3

Each branch of a ternary must be a single expression. Therefore you need to either define your variable outside of the ternary expression, as I show below, or refactor the expression (e.g. encapsulating the behavior in a function or component).

const SomeComponent = (props) => {
  const starrarr = props.starring && JSON.parse(`[${props.starring}]`)

  return (
    <div>
      {props.starring
        ? "..some code"
        : (
          <div className="altactorimg">
            <h6><img src="#" alt="pictures"/>{starrarr[0]}</h6>
            <h6><img src="#" alt="pictures"/>{starrarr[1]}</h6>
            <h6><img src="#" alt="pictures"/>{starrarr[2]}</h6>
          </div>
        )
      }
    </div>
  )
}
coreyward
  • 77,547
  • 20
  • 137
  • 166
  • helpful but react returns a cross origin error. It has to do with JSON.parse. do you have any idea why? – Uriel Sep 02 '20 at 19:56
  • @Uriel The value of `props.starring` is [probably not what you're expecting](https://stackoverflow.com/questions/58266141/why-does-json-parse-throw-a-cross-origin-error). Inspect the value in the React Devtools or console.log it and review. – coreyward Sep 02 '20 at 19:57
  • I do. Its an array. But i just figured it out thanks – Uriel Sep 02 '20 at 20:00
  • 1
    Note that if you expect `props.starring` to be a string like `one,two,three` you would be better served by using `props.starring.split(",")` to create your array. This is safer and more performant than what you show. – coreyward Sep 02 '20 at 20:02
  • thats exactly what i discovered a few min ago. thanks anyways – Uriel Sep 02 '20 at 20:03
  • idk why i was using JSON.parse in the first place lol – Uriel Sep 02 '20 at 20:05
0

After some research i figured it out. Apparently using JSON.parse to convert the string to an array results in a react cross origin error. To solve this problem i used the JS split method to create an array out of the string and everything works perfectly, with no cross origins error.

Thanks for your comments

Uriel
  • 195
  • 1
  • 2
  • 14