There are several different ways to specify props in JSX.
You can pass any JavaScript expression as a prop, by surrounding it with {}
. For example, in this JSX:
<MyComponent count={1 + 2 + 3 + 4} />
Inside the MyComponent
, the value of props.count
will be 10
, because the expression 1 + 2 + 3 + 4
gets evaluated.
If statements and for loops are not expressions in JavaScript, so they can't be used in JSX directly.
Of course, you can just pass any string literal
as a prop
too. These two JSX expressions are equivalent:
<MyComponent message="hello world" />
<MyComponent message={'hello world'} />
When you pass a string literal, its value is HTML-unescaped. So these two JSX expressions are equivalent:
<MyComponent message="<3" />
<MyComponent message={'<3'} />
This behavior is usually not relevant. It's only mentioned here for completeness.
If you pass no value for a prop, it defaults to true
. These two JSX expressions are equivalent:
<MyTextBox autocomplete />
<MyTextBox autocomplete={true} />
However, the React team says in their docs using this approach is not recommended, because it can be confused with the ES6 object shorthand {foo}
which is short for {foo: foo}
rather than {foo: true}
. They say this behavior is just there so that it matches the behavior of HTML.
If you already have props as an object, and you want to pass it in JSX, you can use ...
as a spread operator to pass the whole props object. These two components are equivalent:
function Case1() {
return <Greeting firstName="Kaloyab" lastName="Kosev" />;
}
function Case2() {
const person = {firstName: 'Kaloyan', lastName: 'Kosev'};
return <Greeting {...person} />;
}