JSX supports expression in pure JavaScript syntax. The expression has to be enclosed inside the curly braces, { }. The expression can contain all variables available in the context where the JSX is defined. Let us create simple JSX with expression.
Example
<script type="text/babel">
var currentTime = new Date().toTimeString();
ReactDOM.render(
<div><p>The current time is {currentTime}</p></div>,
document.getElementById('app') );
</script>
Output
Here, cTime is used in the JSX using expression. The output of the above code is as follows,
15:57:48 GMT-0700 (Pacific Daylight Time)
One of the positive side effects of using an expression in JSX is that it prevents Injection attacks as it converts any string into an HTML-safe string.
JSX supports user-defined JavaScript functions. Function usage is similar to expression. Let us create a simple function and use it inside JSX.
Example
<script type="text/babel">
var currentTime = new Date().toTimeString();
ReactDOM.render(
<div><p>The current time is {currentTime}</p></div>,
document.getElementById('app')
);
</script>
Output
Here, getCurrentTime()
is used to get the current time, and the output is similar as specified below −
16:37:32 GMT-0700 (Pacific Daylight Time)