Refer JS variable or function in JSX in ReactJS

When we write our code, we sometimes want to keep some text dynamic rather than static. For example, text of a button or label.

Below is an example to show how to use a JavaScript variable in JSX code. We simply place the JavaScript variable inside curly braces {}.

// Import the React and ReactDOM libraries
import React from 'react';
import ReactDOM from 'react-dom';

// defining a javascript function
function getButtonText(){
    return "Text from function";
}

// Create a React component. This is a function based component.
const App = function() {
    var btnTxt = "Submit";
    return (
<div>
            <label class="label" htmlFor="emailId">Enter Email: </label>
            <input id="emailId" type="text" />
            <button style= {{backgroundColor:"red", color:"white"}}> {btnTxt} </button>
            <button style= {{backgroundColor:"blue", color:"white"}}> {getButtonText()} </button> 
        </div>
    );
};

// Take the React component and display it on the screen. 
// There is div element with id='root' present in index.html in public folder.
ReactDOM.render(
    <App />,
    document.getElementById('root')
);

You can use any type of variable like number, array etc, but you cannot use object.

const btnTxt = 123456;
const btnTxt = "7576hjgj";
const btnTxt = ['Hi','Hello']; //Text displayed on button will be "HiHello"
const btnTxt = ['Hi',1234]; //Text displayed on button will be "Hi1234"
const btnTxt = [100,200]; //Text displayed on button will be "100200"
const btnTxt = {text:"Click Me!"}; //This piece of code will give error as it will not accept code
If you want to use this, you need to make changes to the JSX code. 
<button>btnTxt.text</button>

You will get bellow error if you use JavaScript Object variable in JSX

Other related articles

Introduction to ReactJS
ReactJS Environment Setup
Introduction to JSX
Styling in JSX

Unknown's avatar

Author: Akanksha Gupta

I am a developer and working on SharePoint and Project Server in an MNC. I have more than 10 years of experience in the same field.

Leave a comment

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started