Objects are one of the most useful JavaScript data structures when working with React.
A JavaScript object allows you to store related information together using key-value pairs. In React, objects are commonly used for users, products, settings, API responses, configuration data, and component props.
For example:
const user = {
name: "John",
age: 25,
role: "Developer"
};
You can then access the object’s values inside JSX:
function App() {
const user = {
name: "John",
age: 25,
role: "Developer"
};
return (
<div>
<h1>{user.name}</h1>
<p>Age: {user.age}</p>
<p>Role: {user.role}</p>
</div>
);
}
The object stores the data, while JSX determines how that data appears in the interface.
What Is a JavaScript Object?
An object stores related data using properties.
const product = {
name: "Laptop",
price: 60000,
brand: "ExampleBrand"
};
The object contains three properties:
| Property | Value |
|---|---|
name | "Laptop" |
price | 60000 |
brand | "ExampleBrand" |
You can access each property using dot notation:
product.name
product.price
product.brand
Inside JSX, place the expression inside curly braces:
<h2>{product.name}</h2>
<p>Price: ₹{product.price}</p>
<p>{product.brand}</p>
Creating an Object Inside a Component
Objects are often created inside the component when the data belongs specifically to that component.
function App() {
const student = {
name: "Alex",
course: "React Development",
score: 85
};
return (
<div>
<h2>{student.name}</h2>
<p>{student.course}</p>
<p>Score: {student.score}</p>
</div>
);
}
This approach keeps related information together instead of creating many separate variables.
Instead of:
const name = "Alex";
const course = "React Development";
const score = 85;
you can use:
const student = {
name: "Alex",
course: "React Development",
score: 85
};
Accessing Object Properties in JSX
The most common way to access an object property is dot notation.
const user = {
name: "John",
email: "john@example.com"
};
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
You can use any property whose value can be rendered appropriately.
Using Bracket Notation
JavaScript also supports bracket notation.
const user = {
name: "John",
age: 25
};
return (
<div>
<p>{user["name"]}</p>
<p>{user["age"]}</p>
</div>
);
For normal property names, dot notation is generally easier to read:
{user.name}
Bracket notation becomes particularly useful when the property name is stored in another variable.
const property = "name";
return <h2>{user[property]}</h2>;
Here, JavaScript dynamically determines which property should be accessed.
Using Dynamic Object Properties
A variable can determine which object property to display.
const user = {
name: "John",
role: "Developer",
location: "Hyderabad"
};
const field = "role";
return <p>{user[field]}</p>;
The result is:
Developer
This technique is useful when building reusable components, tables, filters, and dynamic interfaces.
Accessing Nested Objects
Objects can contain other objects.
const user = {
name: "John",
profile: {
city: "Hyderabad",
country: "India"
}
};
You can access nested properties:
<h2>{user.name}</h2>
<p>{user.profile.city}</p>
<p>{user.profile.country}</p>
The expression:
user.profile.city
means:
- Access
user - Access its
profileproperty - Access
cityinsideprofile
Handling Missing Nested Properties
When working with API data, a nested property may not always exist.
For example:
const user = {
name: "John"
};
This can cause a problem:
{user.profile.name}
because profile does not exist.
Optional chaining can safely access the property:
{user.profile?.name}
You can also provide a fallback:
{user.profile?.name ?? "Not available"}
This is especially useful when data is loaded asynchronously from an API.
Rendering Object Values
Individual object properties can be rendered when their values are suitable for React.
For example:
const product = {
name: "Laptop",
price: 60000,
inStock: true
};
return (
<div>
<h2>{product.name}</h2>
<p>₹{product.price}</p>
<p>{product.inStock ? "Available" : "Out of stock"}</p>
</div>
);
Strings, numbers, and appropriate React-renderable values can be displayed directly.
You Cannot Render an Object Directly
One important rule is that you generally cannot render a plain JavaScript object directly as a JSX child.
For example:
const user = {
name: "John",
age: 25
};
return <p>{user}</p>;
This does not tell React how you want the object’s information displayed.
Instead, access the individual properties:
return (
<div>
<p>Name: {user.name}</p>
<p>Age: {user.age}</p>
</div>
);
If you need to inspect an object while debugging, you can convert it to a string:
<pre>{JSON.stringify(user, null, 2)}</pre>
This is useful for debugging or displaying raw JSON-like data.
Rendering Object Properties Dynamically
You can use JavaScript methods to work with object properties.
For example:
const user = {
name: "John",
role: "Developer",
city: "Hyderabad"
};
return (
<ul>
{Object.entries(user).map(([key, value]) => (
<li key={key}>
{key}: {value}
</li>
))}
</ul>
);
Object.entries() converts the object into an array of key-value pairs.
The result can then be processed using .map().
This is useful when you do not know the object’s properties in advance.
Using Object.keys()
Object.keys() returns an array containing the object’s property names.
const user = {
name: "John",
role: "Developer",
city: "Hyderabad"
};
const keys = Object.keys(user);
return (
<ul>
{keys.map((key) => (
<li key={key}>{key}</li>
))}
</ul>
);
The result is a list containing:
name
role
city
You can also use the key to access its corresponding value:
{keys.map((key) => (
<li key={key}>
{key}: {user[key]}
</li>
))}
Using Object.values()
Object.values() returns an array containing the object’s values.
const user = {
name: "John",
role: "Developer",
city: "Hyderabad"
};
const values = Object.values(user);
return (
<ul>
{values.map((value, index) => (
<li key={index}>{value}</li>
))}
</ul>
);
The values are:
John
Developer
Hyderabad
In real applications, however, Object.entries() is often more useful when you need both the property name and value.
Objects Can Contain Arrays
Objects can contain arrays as properties.
const user = {
name: "John",
skills: ["React", "JavaScript", "CSS"]
};
You can access the array:
{user.skills}
But when you want to display each skill individually, use .map():
<ul>
{user.skills.map((skill) => (
<li key={skill}>{skill}</li>
))}
</ul>
This pattern is common when working with structured data.
Objects Can Contain Functions
JavaScript objects can also contain functions.
const user = {
name: "John",
greet() {
return "Hello!";
}
};
The function can be called through the object:
return <p>{user.greet()}</p>;
This is standard JavaScript behavior and can be used inside JSX expressions.
Using Objects for Inline Styles
One of the most common uses of objects in JSX is the style attribute.
React expects an object for inline styles:
<h1 style={{ color: "blue", fontSize: "24px" }}>
Hello React
</h1>
The inner object is:
{
color: "blue",
fontSize: "24px"
}
The outer curly braces tell JSX that JavaScript is being used.
You can also store the style object in a variable:
const headingStyle = {
color: "blue",
fontSize: "24px"
};
return (
<h1 style={headingStyle}>
Hello React
</h1>
);
This can make the JSX cleaner when styles become larger.
JavaScript Property Names in Style Objects
CSS property names are written using JavaScript-style camelCase in JSX style objects.
For example:
const styles = {
backgroundColor: "black",
color: "white",
fontSize: "20px",
marginTop: "10px"
};
Instead of CSS syntax such as:
background-color
font-size
margin-top
React’s JavaScript style object uses:
backgroundColor
fontSize
marginTop
Objects and Component Props
Objects are frequently passed to React components through props.
function App() {
const user = {
name: "John",
role: "Developer"
};
return <UserCard user={user} />;
}
The UserCard component can receive the object:
function UserCard({ user }) {
return (
<div>
<h2>{user.name}</h2>
<p>{user.role}</p>
</div>
);
}
This allows a parent component to provide structured data to a child component.
Destructuring Objects in Components
Instead of repeatedly writing:
user.name
user.role
you can destructure the object.
function UserCard({ user }) {
const { name, role } = user;
return (
<div>
<h2>{name}</h2>
<p>{role}</p>
</div>
);
}
You can also destructure directly in the function parameter:
function UserCard({ user }) {
const { name, role } = user;
return (
<div>
<h2>{name}</h2>
<p>{role}</p>
</div>
);
}
Or, when the props themselves contain name and role:
function UserCard({ name, role }) {
return (
<div>
<h2>{name}</h2>
<p>{role}</p>
</div>
);
}
Destructuring is particularly useful when components receive multiple values through props.
Updating Objects
When working with React state, objects should generally be updated by creating a new object rather than directly mutating the existing one.
For example, with state:
const [user, setUser] = useState({
name: "John",
age: 25
});
To update the age:
setUser({
...user,
age: 26
});
The spread operator copies the existing properties and replaces the age property.
Avoid directly mutating the state object:
user.age = 26;
State and immutable updates are covered in greater detail when learning React state.
Object Spread in JSX
The spread operator can also be used when passing object properties as props.
Suppose you have:
const user = {
name: "John",
age: 25,
role: "Developer"
};
You can pass the properties individually:
<UserCard
name={user.name}
age={user.age}
role={user.role}
/>
Or use object spread:
<UserCard {...user} />
The spread syntax passes the object’s properties as props.
The receiving component can then use:
function UserCard({ name, age, role }) {
return (
<div>
<h2>{name}</h2>
<p>Age: {age}</p>
<p>Role: {role}</p>
</div>
);
}
Use this carefully and clearly, especially when components have many props.
A Complete JSX Objects Example
Here is a practical example combining objects, nested data, arrays, functions, and JSX:
function ProductCard() {
const product = {
name: "Mechanical Keyboard",
brand: "TechBrand",
price: 3500,
rating: 4.5,
inStock: true,
features: [
"RGB Lighting",
"Mechanical Switches",
"USB-C Connection"
]
};
function formatPrice(price) {
return `₹${price.toLocaleString("en-IN")}`;
}
return (
<div className="product-card">
<h2>{product.name}</h2>
<p>Brand: {product.brand}</p>
<p>Price: {formatPrice(product.price)}</p>
<p>Rating: {product.rating}/5</p>
<p>
{product.inStock
? "In Stock"
: "Out of Stock"}
</p>
<h3>Features</h3>
<ul>
{product.features.map((feature) => (
<li key={feature}>{feature}</li>
))}
</ul>
</div>
);
}
The product object keeps all related product information together.
JSX then accesses individual properties and uses the data to build the interface.
Common Mistakes
Trying to Render the Entire Object
Avoid:
<p>{product}</p>
Instead:
<p>{product.name}</p>
Forgetting the Object Property
Incorrect:
<h2>{name}</h2>
when the data is stored inside:
const user = {
name: "John"
};
Correct:
<h2>{user.name}</h2>
Accessing Deep Properties Without Checking
Potentially unsafe:
{user.profile.address.city}
If profile or address does not exist, this can cause an error.
Safer when data may be missing:
{user.profile?.address?.city ?? "Unknown"}
Mutating React State Objects Directly
Avoid:
user.name = "Alex";
when user is state.
Prefer creating a new object:
setUser({
...user,
name: "Alex"
});
Confusing JSX Objects With JSX Elements
These are different:
const user = {
name: "John"
};
This is a JavaScript object.
const element = <h1>Hello</h1>;
This is a JSX element.
Both can be stored in variables, but they serve different purposes.
Where to Place an Image
Image Placement: After “Accessing Object Properties in JSX”
Create a 16:9 React infographic showing a JavaScript object flowing into JSX.
Show:
const user = {
name: "John",
age: 25,
role: "Developer"
};
↓
{user.name}
{user.age}
{user.role}
↓
React UI
Visually highlight the relationship between object properties and their corresponding JSX output.
Caption:
React JSX can access individual JavaScript object properties to display structured data.
Alt text:
JSX objects infographic showing a JavaScript user object and its properties being displayed in a React interface.
Practice Exercise
Create a StudentCard component using this object:
const student = {
name: "Alex",
age: 21,
course: "React Development",
score: 88,
isOnline: true,
skills: [
"HTML",
"CSS",
"JavaScript",
"React"
]
};
Use JSX to display:
- Student name
- Age
- Course
- Score
- Online or offline status
- List of skills
Then create a function:
function getResult(score) {
return score >= 40 ? "Passed" : "Failed";
}
Use it inside JSX:
<p>Result: {getResult(student.score)}</p>
Finally, try destructuring the object:
const { name, age, course, score } = student;
and use the destructured variables in your JSX.
Key Takeaways
JavaScript objects are extremely useful when working with structured data in React.
Remember:
- Objects store related information as key-value pairs.
- Access object properties using expressions such as
{user.name}. - Bracket notation can access dynamic property names.
- Objects can contain nested objects and arrays.
- Optional chaining helps safely access potentially missing nested data.
- A plain JavaScript object should not normally be rendered directly as a JSX child.
Object.keys(),Object.values(), andObject.entries()can help work with dynamic objects.- Objects are commonly used for component props.
- Objects are used to define inline style values.
- Destructuring makes object data easier to work with.
- React state objects should be updated without directly mutating the existing object.
- Object spread is useful for creating updated objects and passing groups of props.
The basic pattern is:
JavaScript Object
↓
Object Property
↓
{user.name}
↓
JSX
↓
React UI
Once objects are clear, the next step is JSX Arrays, where you’ll learn how React works with collections of data and turns array items into lists of JSX elements.