Functions are an important part of JavaScript and React. They allow you to organize logic into reusable blocks of code and are used throughout React applications.
When working with JSX, functions can be used to calculate values, format data, return JSX, handle events, and perform other tasks needed by a component.
For example:
function getGreeting() {
return "Welcome to React!";
}
function App() {
return <h1>{getGreeting()}</h1>;
}
The getGreeting() function returns a string, and the returned value is displayed inside the JSX.
Functions become even more important when you start working with React components, event handling, props, state, and reusable UI logic.
What Are Functions in JSX?
JSX can use JavaScript function calls inside curly braces.
function getName() {
return "John";
}
function App() {
return <h1>{getName()}</h1>;
}
Here:
{getName()}
is a JavaScript expression.
React evaluates the function call and uses its returned value in the JSX.
The basic flow is:
Function
↓
Function call
↓
Returned value
↓
JSX
↓
React UI
Creating a Function
A function can be declared before the component.
function getMessage() {
return "Hello React!";
}
The function can then be called inside the component:
function App() {
return <h1>{getMessage()}</h1>;
}
You can also define a function inside a component.
function App() {
function getMessage() {
return "Hello React!";
}
return <h1>{getMessage()}</h1>;
}
Both approaches can be useful depending on whether the function needs access to component-specific values.
Calling a Function Inside JSX
To call a function and display its returned value, use the function name followed by parentheses.
function getGreeting() {
return "Good morning!";
}
function App() {
return (
<div>
<h1>{getGreeting()}</h1>
</div>
);
}
The important difference is between:
{getGreeting}
and:
{getGreeting()}
The first refers to the function itself.
The second calls the function and uses the value it returns.
When you want the result of a function, you normally need the parentheses.
Functions Can Return Strings
A function can return text that is displayed in JSX.
function getTitle() {
return "React Developer";
}
function App() {
return <h2>{getTitle()}</h2>;
}
This is useful for formatting or generating dynamic text.
Functions Can Return Numbers
Functions can also return numbers.
function calculateTotal() {
return 1000 + 500;
}
function App() {
return <p>Total: ₹{calculateTotal()}</p>;
}
The function performs the calculation and returns the result.
For more realistic applications:
function calculateTotal(price, quantity) {
return price * quantity;
}
function App() {
return (
<p>
Total: ₹{calculateTotal(2500, 2)}
</p>
);
}
Passing Arguments to Functions
Functions can receive values through parameters.
function greet(name) {
return `Hello, ${name}!`;
}
function App() {
return <h1>{greet("John")}</h1>;
}
You can also pass variables:
function greet(name) {
return `Hello, ${name}!`;
}
function App() {
const name = "John";
return <h1>{greet(name)}</h1>;
}
This allows the same function to work with different values.
For example:
<h1>{greet("John")}</h1>
<h1>{greet("Alex")}</h1>
<h1>{greet("Sarah")}</h1>
Functions Can Format Data
Functions are often useful for preparing data before displaying it.
For example:
function formatPrice(price) {
return `₹${price.toLocaleString("en-IN")}`;
}
function App() {
const price = 125000;
return <p>Price: {formatPrice(price)}</p>;
}
Another example:
function formatName(name) {
return name.toUpperCase();
}
function App() {
const name = "john";
return <h1>{formatName(name)}</h1>;
}
The function handles the formatting while JSX handles the presentation.
Functions Can Work With Objects
A function can receive an object and return information from it.
function getUserName(user) {
return user.name;
}
function App() {
const user = {
name: "John",
role: "Developer"
};
return <h2>{getUserName(user)}</h2>;
}
You can also use destructuring:
function getUserName({ name }) {
return name;
}
This becomes useful when working with structured application data.
Functions Can Work With Arrays
Functions can process arrays before the result is displayed.
function getTotal(numbers) {
return numbers.reduce((total, number) => total + number, 0);
}
function App() {
const prices = [100, 200, 300];
return <p>Total: ₹{getTotal(prices)}</p>;
}
Another example is counting items:
function getItemCount(items) {
return items.length;
}
function App() {
const products = ["Laptop", "Phone", "Tablet"];
return <p>Products: {getItemCount(products)}</p>;
}
Functions Can Return JSX
Functions do not have to return strings or numbers. They can also return JSX.
function WelcomeMessage() {
return <h1>Welcome to React!</h1>;
}
function App() {
return (
<div>
{WelcomeMessage()}
</div>
);
}
The function returns a JSX element.
However, when the function represents a reusable UI component, it is usually better to make it a React component and use component syntax:
function WelcomeMessage() {
return <h1>Welcome to React!</h1>;
}
function App() {
return (
<div>
<WelcomeMessage />
</div>
);
}
This distinction becomes important as your React applications grow.
Functions and React Components
A React function component is itself a JavaScript function that returns JSX.
function App() {
return (
<div>
<h1>Hello React</h1>
<p>Welcome to my application.</p>
</div>
);
}
The App function is a React component.
React calls the component and uses the returned JSX to determine what should appear in the UI.
This means functions are fundamental to React.
Functions Can Be Used for Conditional Content
A function can contain logic and return different values.
function getStatus(isOnline) {
if (isOnline) {
return "Online";
}
return "Offline";
}
function App() {
const isOnline = true;
return <p>Status: {getStatus(isOnline)}</p>;
}
The function handles the condition, while JSX displays the result.
This can be useful when the logic is reused or becomes too complicated for a simple JSX expression.
Functions Can Return Different JSX
A function can also return different JSX depending on a condition.
function getMessage(isLoggedIn) {
if (isLoggedIn) {
return <p>Welcome back!</p>;
}
return <p>Please log in.</p>;
}
function App() {
const isLoggedIn = true;
return (
<div>
{getMessage(isLoggedIn)}
</div>
);
}
For simple conditions, however, a ternary directly inside JSX may be easier to read:
{isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>}
Use a function when it makes the logic clearer or reusable.
Functions and Event Handlers
Functions are especially important when responding to user actions.
For example:
function App() {
function handleClick() {
console.log("Button clicked");
}
return (
<button onClick={handleClick}>
Click Me
</button>
);
}
Here, handleClick is passed to onClick.
Notice that there are no parentheses:
onClick={handleClick}
You are passing the function itself so React can call it when the event happens.
Do not write:
onClick={handleClick()}
That calls the function immediately during rendering instead of waiting for the click.
Calling a Function With Arguments in an Event
If you need to pass an argument to a function, use another function.
function showMessage(name) {
console.log(`Hello, ${name}`);
}
function App() {
return (
<button onClick={() => showMessage("John")}>
Say Hello
</button>
);
}
The arrow function waits until the button is clicked.
When the click happens, it calls:
showMessage("John")
Functions Can Be Used With Multiple Buttons
The same function can be reused with different values.
function greet(name) {
console.log(`Hello, ${name}`);
}
function App() {
return (
<div>
<button onClick={() => greet("John")}>
John
</button>
<button onClick={() => greet("Alex")}>
Alex
</button>
<button onClick={() => greet("Sarah")}>
Sarah
</button>
</div>
);
}
This avoids creating separate functions for every button.
Arrow Functions in JSX
Arrow functions are frequently used in React.
For example:
const greet = () => {
return "Hello!";
};
This can be shortened:
const greet = () => "Hello!";
You can then use it:
<h1>{greet()}</h1>
Arrow functions are also commonly used with event handlers:
<button onClick={() => console.log("Clicked")}>
Click Me
</button>
And with array methods:
items.map((item) => (
<li key={item.id}>{item.name}</li>
))
Immediately Calling Functions in JSX
A function can be called directly inside JSX when you want its returned value.
function getMessage() {
return "Hello React";
}
return <h1>{getMessage()}</h1>;
This is different from an event handler:
<button onClick={getMessage}>
Click
</button>
Here, the function is passed without parentheses because React should call it later when the event occurs.
The distinction is important:
| Situation | Syntax |
|---|---|
| Get function result during rendering | {getMessage()} |
| Give function to event handler | onClick={getMessage} |
| Call with event-time arguments | onClick={() => getMessage(value)} |
Functions Can Access Component Variables
Functions declared inside a component can access variables available in that component’s scope.
function App() {
const name = "John";
function getGreeting() {
return `Hello, ${name}!`;
}
return <h1>{getGreeting()}</h1>;
}
The function can access name because it is declared within the same component scope.
This becomes particularly useful when functions need to work with component data.
Functions Can Be Used for Formatting
Instead of putting complicated formatting directly inside JSX, create a function.
For example:
function formatName(firstName, lastName) {
return `${firstName} ${lastName}`;
}
function App() {
return (
<h1>
{formatName("John", "Smith")}
</h1>
);
}
Another example:
function formatDate(date) {
return date.toLocaleDateString("en-IN");
}
function App() {
const date = new Date();
return <p>{formatDate(date)}</p>;
}
This keeps formatting logic separate from the JSX structure.
Functions and Props
Functions can be passed from one React component to another using props.
For example:
function Button({ onClick }) {
return (
<button onClick={onClick}>
Click Me
</button>
);
}
function App() {
function handleClick() {
console.log("Button clicked");
}
return <Button onClick={handleClick} />;
}
Here:
handleClick
is passed from App to Button.
The child component can then call it through the onClick event.
Functions passed through props are a fundamental part of communication between React components.
Functions Can Receive Props
A component function can receive props as an argument.
function User({ name }) {
return <h2>Hello, {name}</h2>;
}
function App() {
return <User name="John" />;
}
The User component is a function, and React provides its props to that function.
This means React components combine two concepts:
JavaScript Functions
+
JSX
↓
React Components
Functions Should Usually Be Pure
When a function is used during rendering, it should generally calculate a result rather than perform unexpected side effects.
For example:
function formatName(name) {
return name.toUpperCase();
}
This function receives a value and returns a result without changing anything outside itself.
That makes it predictable.
Avoid using rendering functions for operations such as:
- Changing external data
- Starting timers
- Making unexpected network requests
- Modifying the DOM directly
- Performing other side effects
React provides specific patterns and hooks for side effects, which are covered later.
Avoid Changing Data During Rendering
A function called while JSX is rendering should not unexpectedly modify the data being rendered.
For example, avoid patterns such as:
function addItem(items) {
items.push("New Item");
return items;
}
Instead, create a new array:
function addItem(items) {
return [...items, "New Item"];
}
This approach avoids mutating the original array.
Immutability becomes especially important when working with React state.
A Complete JSX Functions Example
Here is a practical example that combines several concepts:
function formatPrice(price) {
return `₹${price.toLocaleString("en-IN")}`;
}
function getStockMessage(inStock) {
return inStock ? "In Stock" : "Out of Stock";
}
function ProductCard() {
const product = {
name: "Wireless Headphones",
price: 2500,
quantity: 2,
inStock: true
};
function calculateTotal(price, quantity) {
return price * quantity;
}
function handleBuy() {
console.log(`Buying ${product.name}`);
}
const total = calculateTotal(
product.price,
product.quantity
);
return (
<div className="product-card">
<h2>{product.name}</h2>
<p>Price: {formatPrice(product.price)}</p>
<p>Quantity: {product.quantity}</p>
<p>Total: {formatPrice(total)}</p>
<p>{getStockMessage(product.inStock)}</p>
<button
onClick={handleBuy}
disabled={!product.inStock}
>
Buy Now
</button>
</div>
);
}
This example uses functions for:
- Formatting prices
- Calculating totals
- Generating stock messages
- Handling button clicks
Each function has a specific responsibility, which makes the component easier to understand.
Function Usage Cheat Sheet
| Purpose | Example |
|---|---|
| Call a function in JSX | {getName()} |
| Pass function to event | onClick={handleClick} |
| Pass argument to event | onClick={() => handleClick(id)} |
| Function with parameter | function greet(name) |
| Function returning text | return "Hello" |
| Function returning number | return price * quantity |
| Function returning JSX | return <p>Hello</p> |
| Arrow function | const greet = () => "Hello" |
| Format data | {formatPrice(price)} |
| Process arrays | {items.map(...)} |
| Pass function as prop | <Button onClick={handleClick} /> |
Common Mistakes
Calling an Event Handler Immediately
Incorrect:
<button onClick={handleClick()}>
Click
</button>
Correct:
<button onClick={handleClick}>
Click
</button>
React should receive the function and call it when the event occurs.
Forgetting to Call a Function
If you need the function’s returned value:
<h1>{getGreeting()}</h1>
not:
<h1>{getGreeting}</h1>
The second version refers to the function itself rather than its returned result.
Putting Too Much Logic Inside JSX
Avoid making JSX difficult to read:
<p>
{products.filter(p => p.inStock)
.map(p => p.price)
.reduce((a, b) => a + b, 0)}
</p>
For complicated logic, calculate the result before the return:
const availableProducts = products.filter(
(product) => product.inStock
);
const total = availableProducts.reduce(
(sum, product) => sum + product.price,
0
);
return <p>Total: ₹{total}</p>;
The second version is easier to understand.
Using Functions for Unnecessary Work
Do not create a function when a simple expression is clearer.
Instead of:
function getName() {
return name;
}
return <h1>{getName()}</h1>;
simply use:
return <h1>{name}</h1>;
Functions are most useful when they provide meaningful logic, reuse, formatting, or event handling.
Where to Place an Image
Image Placement: After “Calling a Function Inside JSX”
Create a 16:9 React infographic showing:
function getGreeting() {
return "Hello!";
}
↓
{getGreeting()}
↓
<h1>Hello!</h1>
↓
React UI
Use a modern developer-themed design with a clear visual distinction between the function, function call, returned value, and rendered UI.
Caption:
Functions can calculate or return values that JSX displays in the React interface.
Alt text:
JSX functions infographic showing a JavaScript function returning a value that is displayed through JSX.
Practice Exercise
Create a ProductCard component using this data:
const product = {
name: "Mechanical Keyboard",
price: 3500,
quantity: 2,
inStock: true
};
Create the following functions:
function formatPrice(price) {
// Format the price
}
function calculateTotal(price, quantity) {
// Calculate the total
}
function getStockMessage(inStock) {
// Return "In Stock" or "Out of Stock"
}
Use those functions inside your JSX.
Then create an event handler:
function handleBuy() {
console.log("Product purchased");
}
Connect it to a button using:
onClick={handleBuy}
Try adding a second button that passes the product name to a function:
onClick={() => showProduct(product.name)}
This exercise will help you understand the difference between calling a function, passing a function, and passing arguments to a function.
Key Takeaways
Functions and JSX work together to make React components dynamic and reusable.
Remember:
- JSX can call JavaScript functions inside
{}. - A function call uses parentheses, such as
{getName()}. - Functions can return strings, numbers, JSX, or other values.
- Functions can receive parameters and arguments.
- Functions are useful for formatting and calculating data.
- Functions can process objects and arrays.
- React components themselves are JavaScript functions that return JSX.
- Event handlers receive functions, such as
onClick={handleClick}. - Use an arrow function when you need to pass arguments to an event handler.
- Functions can be passed between components through props.
- Keep complicated logic outside JSX when it improves readability.
- Functions used during rendering should generally avoid side effects.
- Regular JavaScript functions and React components serve different purposes, even though both are built with functions.
The key pattern is:
Function
↓
Process Data / Perform Logic
↓
Return Value
↓
JSX
↓
React UI
Functions become even more powerful when combined with objects and arrays, which allow React components to work with structured collections of data.