Contradiction in examples given in JSX conditionals


#1


https://www.codecademy.com/courses/react-101/lessons/react-jsx-advanced/exercises/jsx-conditionals-valid-if?action=resume


Here is something that frustrates me about the example given. If.js is as follows:

if (user.age >= drinkingAge) {
  var message = (
    <h1>
      Hey, check out this alcoholic beverage!
    </h1>
  );
} else {
  var message = (
    <h1>
      Hey, check out these earrings I got at Claire's!
    </h1>
  );
}

This makes it seem as if JSX elements can be used inside conditionals, as long as you end add ";" to the closing parenthesis.

The code below is the code the project provides in app.js along with my answer:

var React = require('react');
var ReactDOM = require('react-dom');

function coinToss () {
  // This function will randomly return either 'heads' or 'tails'.
  return Math.random() < 0.5 ? 'heads' : 'tails';
}

var pics = {
  kitty: 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-kitty.jpg',
  doggy: 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-puppy.jpeg'
};

// if/else statement begins here:
if (coinToss() == 'heads') {
  var img = (
    <img src={pics.kitty} />;
  );
} else{
  var img = (
    <img src={pics.doggy} />;
    );
}

ReactDOM.render(img,
                document.getElementById('app')


);

Why is it that when I create a JSX element around image tags, the compiler throws an error? It's laid out exactly the same way as the example but using <img /> instead of <h1> </h1>.

Am I just missing something? The syntax matches all other lessons (and the example) exactly from what I can tell.


#2

These lines are the problems:

var img = (
    <img src={pics.kitty} />;
  );

And:

var img = (
    <img src={pics.doggy} />;
    );

You don't need to end your <img /> tags with semicolons as that's handled after your closing brackets at the end of the lines. In a way, the parentheses sort of extend your line.

If you were doing the code like this:

var img = <img src={pics.kitty} />;

Then you would need the semicolon as it's the end of the line.

Your code is basically the same as doing this:

var img = ( <img src={pics.kitty} /> );

As you can see, the semicolon is at the end of the line.

If this helped, please mark this answer as the solution. Thanks :slight_smile:


#3

Ah I see!!

That's fantastic, thank you! I was racking my brain trying to figure out what I was missing lol. Appreciate your time :slight_smile:


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.