How to reference Javascript variables in JSX?

How to use JSX in React.js? »

JSX is a dialect of Javascript itself, therefore, referencing Javascript variables in JSX is super easy. Let’s get back to the index.js file and try to create a variable named myName that stores “Gautam Kabiraj”. The complete code would look like:

// Import Libraries
import React from 'react';
import ReactDOM from 'react-dom';

// Create React Component and reference a variable to it
const App = function() {

const myName = "Gautam Kabiraj";

return 
<div>

<h1 style={{ color: 'red'}} >
{myName}
</h1>

</div>;
};

// Show React Component on the browser
ReactDOM.render(
<App/>,
document.querySelector('#root')
);

As you can see, I’ve simply stored my name (Gautam Kabiraj) in a variable named myName using Javascript. Later, I’ve used that variable in my JSX code using { myName } syntax. That is how you access a javascript variable (using a single pair of curly braces).

You can also define Javascript functions (to reference javascript variables in jsx), which’ll do something and return some value to be printed wherever it is being called. Look at the below example:

// Import Libraries
import React from 'react';
import ReactDOM from 'react-dom';

// Function to return her name
function callHerName() {
const herName = "Vincy Kabiraj";
return herName;
}

// Create React Component and reference a variable and a function to it
const App = function() {
const myName = "Gautam Kabiraj";
return 
<div>

<h1 style={{ color: 'red'}} >
{myName} loves {callHerName()}
</h1>

</div>

;
};

// Show React Component on the browser
ReactDOM.render(
<App/>,
document.querySelector('#root')
);

In the above code, I’ve first defined a function named callHerName that returns “Vincy Kabiraj” wherever it is being called. Next, inside the App function, I’ve created a variable named myName that stores “Gautam Kabiraj”. Later, inside the h1 tags, I’ve wrote JSX syntax:

{myName} loves {callHerName()}

Here, myName is replaced by “Gautam Kabiraj” and callHerName is replaced by “Vincy Kabiraj”. So, the resultant output becomes:

Gautam Kabiraj loves Vincy Kabiraj

Take note that whenever you make function calls inside JSX, parenthesis () are compulsory just as any other programming language demands.

Leave a Comment