Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript React Basics Introducing Props Components and Props

Routine Poutine
Routine Poutine
26,038 Points

Why does JSX allow for strings without {}, but not numbers and booleans? "My Scoreboard" is OK, but not {5}.

Hi,

Why is it OK to use a "string" without {}, but not a number {5} or boolean {true}? Why aren't we required to put {"string"}?

3 Answers

Marco Fregoso
Marco Fregoso
405 Points

You can pass in the boolean or number value but since you're passing it directly it'll be parsed in as a string representation of that value. Let's say you passed the number 1 directly without curly braces.

const Container = () => {
  return (
    <div>
      <Component passedValue="1" />
    </div>
  );
}

If you then tried to test what type of value the passed number is it would return a string which could cause annoying bugs if you tried to do something with the value.

const Component = (props) => {
  console.log(typeof props.passedValue); // logs 'string' to the console
  return ....
}

If on the other hand you were to pass the number in a JS expression with the value of 1 between curly braces it would be a number type.:

...
   <Component passedValue={1} />
...
...

const Component = (props) => {
  console.log(typeof props.passedValue); // logs 'number' to the console
  return ....
}
MD MONIRUZZAMAN
MD MONIRUZZAMAN
6,129 Points

This { } Curly braces lets JSX know that it's a javascript expression & need to evaluate. Like isFun={true}. When we use { } in JSX ,it's called a JSX expression

<Header 
  title="My Scoreboard" 
  totalPlayers={5}
  isFun={true}
/>

Great question. My understanding is that as the JSX mimics the name/value attribute system from HTML, you must pass it either a string like you would in HTML <a href="www.google.com"></a> (the href portion of that tag is the attribute) or to delineate a different method, you must use the expression evaluator {}.

As someone mentioned above, passing a number in quotes would evaluate to a string and you would have to do type conversion or check the string value to use it as a number (not very handy or fun).