Reputation: 10235
A few days ago I asked about placing JS within JSX. However, I would like to ask about the reverse here. Is it possible to place JSX within JavaScript? Apparently, it does work, as in the following code... But I am confused about why!
return (
// comments work here, outside of the `<div></div>` segment
<div className="contact-card">
<img src="https://via.placeholder.com/150" alt="profile" />
<div className="user-details">
<p>Name: Jenny Han</p>
<p>Email: [email protected]</p>
{
// But within this `<div></div>` segment,
// JavaScript has to be enclosed within `{}`
// So this is a JavaScript segment now,
// But why does `<p>Age: 25</p>` JSX work here?
showAge && <p>Age: 25</p>
}
</div>
</div>
// Comments work here too!
);
};
Upvotes: 0
Views: 62
Reputation: 14201
As I mentioned in my comment, this is the work of JavaScript compilers (or transpiler - whichever you prefer) such as Babel. For example in Babel, in their website you can see a sample of how they transform your JSX source code into JavaScript that the browser engines can understand. That is why JSX works within JS
The transforming of the code is necessary because browser engines by default does not understand your JSX. As stated in the JSX Specifications:
JSX is NOT intended to be implemented by engines or browsers. It's NOT a proposal to incorporate JSX into the ECMAScript spec itself.
JSX is an expression too so that is why it immediately works in your example above.
Expressions: https://en.wikipedia.org/wiki/Expression_(computer_science)
Here is its syntax: https://facebook.github.io/jsx/#syntax
function App(){
const sampleRetExpression = () => { return "yo" };
return (
<React.Fragment>
{true && <div>Hello, world!</div>}
{true && 101}
{true && sampleRetExpression()}
</React.Fragment>
);
}
ReactDOM.render(<App/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
<div id="other"></div>
Upvotes: 0
Reputation: 5946
https://reactjs.org/docs/introducing-jsx.html
Embedding Expressions in JSX
You can put any valid JavaScript expression inside the curly braces in JSX
JSX is an Expression Too
After compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects.
This means that you can use JSX inside of if statements and for loops, assign it to variables, accept it as arguments, and return it from functions
In other words, you can include JSX directly within JS and JS within JSX (as long as the JS is enclosed within braces), and so on.
Upvotes: 0