React JSX
24 April 2025 | Category: React Js
JSX (JavaScript XML) is a syntax extension that allows you to write HTML-like code within JavaScript, making it easier to build dynamic and interactive user interfaces in React. In this guide, you’ll learn the fundamentals of JSX, including its syntax, how to embed expressions, handle attributes, and render lists and conditionals. We’ll apply these concepts by building a Profile Card Generator app that lets users create and display profile cards.
By the end, you’ll be confident using JSX to create reusable React components.
What is JSX?
JSX is a syntax that combines HTML-like markup with JavaScript, used in React to define the structure and appearance of UI components. It looks like HTML but is transformed into JavaScript function calls (e.g., React.createElement
) during compilation. JSX makes React code more readable and intuitive, especially for developers familiar with HTML.
Why Use JSX in React?
- Readable Code: Write UI structures that resemble HTML, improving clarity.
- Dynamic Rendering: Embed JavaScript expressions to create dynamic content.
- Component-Based: Combine JSX with components for reusable UI pieces.
- Modern Workflow: Supported by tools like Create React App and Vite, with no need to import React in React 19.
Prerequisites
Before starting, ensure you have:
- Basic knowledge of React (components, props) and JavaScript (ES6).
- Node.js and npm installed (download from nodejs.org).
- A code editor like Visual Studio Code.
- A terminal for running commands.
We’ll use Create React App to set up our project, which supports JSX and ES6 out of the box.
Key JSX Concepts
Let’s explore the core features of JSX that you’ll use in React.
1. JSX Syntax
JSX looks like HTML but follows strict rules:
- Must return a single parent element (wrap multiple elements in a
<div>
or fragment<>...</>
). - Tags must be closed (e.g.,
<br />
or<div></div>
). - Uses camelCase for attributes (e.g.,
className
instead ofclass
).
Example:
const Element = () => {
return <div>Hello, JSX!</div>;
};
2. Embedding Expressions
Use curly braces {}
to embed JavaScript expressions in JSX, such as variables, calculations, or function calls.
Example:
const name = 'Alice';
const Greeting = () => {
return <p>Welcome, {name.toUpperCase()}!</p>;
};
3. JSX Attributes
Attributes in JSX use camelCase (e.g., onClick
, className
). You can pass static values or dynamic expressions using {}
.
Example:
const Button = () => {
const label = 'Click Me';
return <button className="btn" onClick={() => alert('Clicked!')}>{label}</button>;
};
4. Conditionals in JSX
Use JavaScript conditionals (e.g., if, ternary operators, or logical &&
) to render elements conditionally.
Example:
const Status = ({ isOnline }) => {
return <p>{isOnline ? 'Online' : 'Offline'}</p>;
};
5. Rendering Lists
Use map()
to render lists of elements, ensuring each child has a unique key
prop to optimize rendering.
Example:
const TaskList = ({ tasks }) => {
return (
<ul>
{tasks.map((task) => (
<li key={task.id}>{task.title}</li>
))}
</ul>
);
};
6. Fragments
Use <>...</>
(React Fragments) to group elements without adding extra DOM nodes.
Example:
const Group = () => {
return (
<>
<h1>Title</h1>
<p>Description</p>
</>
);
};
Setting Up the Project
Let’s create a React app to build our Profile Card Generator, which will use JSX to render dynamic profile cards based on user input.
Create a New React App:
- Open your terminal and run:
npx create-react-app profile-card-generator cd profile-card-generator
- Start the Development Server:
npm start
This opens your app athttp://localhost:3000
.
Clean Up:
- Open
src/App.js
and replace its content with:const App = () => { return ( <div> <h1>Profile Card Generator</h1> </div> ); }; export default App;
- Delete
src/App.css
,src/logo.svg
, and updatesrc/index.css
with:body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f5f5f5; } h1 { color: #333; }
Building the Profile Card Generator App
Our Profile Card Generator app will:
- Allow users to input their name, job title, and status (online/offline).
- Display a list of profile cards with dynamic JSX content.
- Use conditionals to show status badges and map to render multiple cards.
Step 1: Create the ProfileCard
Component
In src
, create a file named ProfileCard.js
:
const ProfileCard = ({ name, job, isOnline }) => {
return (
<div style={{ backgroundColor: '#fff', padding: '20px', margin: '10px 0', borderRadius: '8px', boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)', maxWidth: '300px' }}>
<h2>{name}</h2>
<p>Job: {job}</p>
<span style={{ padding: '5px 10px', backgroundColor: isOnline ? '#28a745' : '#dc3545', color: '#fff', borderRadius: '4px' }}>
{isOnline ? 'Online' : 'Offline'}
</span>
</div>
);
};
export default ProfileCard;
Step 2: Create the ProfileForm
Component
In src
, create a file named ProfileForm.js
:
const ProfileForm = ({ onAddProfile }) => {
const [name, setName] = React.useState('');
const [job, setJob] = React.useState('');
const [isOnline, setIsOnline] = React.useState(false);
const handleSubmit = (e) => {
e.preventDefault();
if (name.trim() && job.trim()) {
onAddProfile({ name, job, isOnline });
setName('');
setJob('');
setIsOnline(false);
}
};
return (
<form onSubmit={handleSubmit} style={{ marginBottom: '20px' }}>
<div style={{ marginBottom: '10px' }}>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter name"
style={{ padding: '8px', width: '200px', borderRadius: '4px' }}
/>
</div>
<div style={{ marginBottom: '10px' }}>
<input
type="text"
value={job}
onChange={(e) => setJob(e.target.value)}
placeholder="Enter job title"
style={{ padding: '8px', width: '200px', borderRadius: '4px' }}
/>
</div>
<div style={{ marginBottom: '10px' }}>
<label>
<input
type="checkbox"
checked={isOnline}
onChange={(e) => setIsOnline(e.target.checked)}
/>{' '}
Online
</label>
</div>
<button
type="submit"
style={{ padding: '8px 16px', backgroundColor: '#007bff', color: '#fff', border: 'none', borderRadius: '4px' }}
>
Add Profile
</button>
</form>
);
};
export default ProfileForm;
Step 3: Update the App
Component
Update src/App.js
to manage profiles and render the components:
import ProfileCard from './ProfileCard';
import ProfileForm from './ProfileForm';
const App = () => {
const [profiles, setProfiles] = React.useState([
{ name: 'Alice Smith', job: 'Designer', isOnline: true },
{ name: 'Bob Jones', job: 'Developer', isOnline: false }
]);
const addProfile = (newProfile) => {
setProfiles([...profiles, newProfile]);
};
return (
<>
<h1>Profile Card Generator</h1>
<ProfileForm onAddProfile={addProfile} />
<div>
{profiles.length > 0 ? (
profiles.map((profile, index) => (
<ProfileCard key={index} name={profile.name} job={profile.job} isOnline={profile.isOnline} />
))
) : (
<p>No profiles yet. Add one!</p>
)}
</div>
</>
);
};
export default App;
Conclusion
You’ve built a Profile Card Generator using JSX in React! You learned how to handle JSX syntax, embed expressions, use attributes, and manage conditional rendering. With these fundamental skills, you can now create dynamic user interfaces in React.
Feel free to expand the app by adding more features like profile editing, deletion, or profile picture uploads.
Happy coding!