Menu

JSX Expressions in ReactJS: Variables, Ternary & Examples

Using Variables and Expressions in JSX

What Can Go Inside Curly Braces?

Any JavaScript expression anything that produces a value.

Example

src/components/StudentCard.jsx

function StudentCard() {
  const student = {
    name: "Arjun Mehta",
    course: "React Development",
    lessonsCompleted: 18,
    totalLessons: 40
  };

  const progress = Math.round((student.lessonsCompleted / student.totalLessons) * 100);

  return (
    <div className="student-card">
      <h2>{student.name}</h2>
      <p>Course: {student.course}</p>
      <p>Lessons: {student.lessonsCompleted} of {student.totalLessons}</p>
      <p>Progress: {progress}%</p>
      <p>Status: {progress >= 50 ? "On track" : "Needs attention"}</p>
    </div>
  );
}

export default StudentCard;

How It Works

  • {student.name} - object property access works normally.
  • {progress} - a value calculated above the return. Complex logic belongs above the return statement, not inside JSX.
  • {student.lessonsCompleted} of {student.totalLessons} - you can use multiple expressions in one line.
  • {progress >= 50 ? "On track" : "Needs attention"} - a ternary operator. This is how you do conditionals inside JSX; if statements do not work inside curly braces because if is a statement, not an expression.

Output

Arjun Mehta
Course: React Development
Lessons: 18 of 40
Progress: 45%
Status: Needs attention

What Does Not Work Inside Braces

Works

Does not work

Variables, object propertiesif / else statements
Function callsfor loops
Arithmetic and comparisonsswitch statements
Ternary operator ? :Variable declarations
.map() on arrays 

For anything on the right-hand column, do the work above the return and use the result inside JSX.


ReactJS Tutorial

VA

Vishalini A



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details