MOCKSTACKS
EN
Questions And Answers

More Tutorials









React JSX

Props in JSX


There are several different ways to specify props in JSX.
JavaScript Expressions

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.
String Literals

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.

Props Default Value

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.

Spread Attributes

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} />;
}



Conclusion

In this page (written and validated by ) you learned about React JSX . What's Next? If you are interested in completing React tutorial, your next topic will be learning about: React Forms.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.