0

I am trying to display a special instruction section only if a user has entered one. I am trying to do it with a condition statement but it just prints out ? Special Instructions : "";

I come from a php background and I am a little new to react. I am not sure what i am doing wrong. Below is my code. Any help would be really appreciated!

const OrderDetails = ({match,orders}) => {    
  const index = _.findIndex(orders,{id:match.params.id});    
  const order_deets_obj = orders[index];

  const order_deets = 
     <div>
      <div>{order_deets_obj.full_name} </div>
      <div>{order_deets_obj.address} </div>
      <div><button>Adjust</button> <button> Cancel </button> </div>
      {order_deets_obj.special_instrusctions !== ""} ? <div>Special Instructions</div> : "";
    </div>

  return order_deets
}
FoundingBox
  • 580
  • 2
  • 7
json
  • 177
  • 1
  • 9
  • Your ? is not in a javascript brace {}. It's just literally text. Just like if you wrote any other text in that area. Move your brace to the right to encompass your ternary if you wish for text to be compiled as javascript. – Yuji 'Tomita' Tomita Jan 08 '21 at 02:40

2 Answers2

0

Put the whole thing in the braces:

{order_deets_obj.special_instrusctions !== "" ? <div>Special Instructions</div> : ""}
Zac Anger
  • 6,983
  • 2
  • 15
  • 42
0

In this particular case, it seems like you want to conditionally render a div which means you can use the && operator rather than the ternary operator.

You can use the following syntax to conditionally render it.

{order_deets_obj.special_instructions && <div>Special Instructions</div>}

Here's more documentation on conditional rendering in React

Note: Since you're new to javascript its handy to know that the conditions someString and someString !== "" are equivalent. Unless you need to explicitly check if the string is null. Here's a good StackOverflow post explaining it

FoundingBox
  • 580
  • 2
  • 7
  • 1
    I actually like your solution better for its brevity, but just to be clear, it does not employ the ternary operator as the OP explicitly asked for. The ternary operator syntax is: `condition ? exprIfTrue : exprIfFalse`. With that said, I agree with you that it would be unnecessary. – codemonkey Jan 12 '21 at 05:24