Building with React: Dive into JSX, Components, and Props! (React Day 2)
Source: Dev.to
đ Welcome Back, React RookiesâTurnedâPros!
After DayâŻ1âs bigâpicture overview, today we dive into the core pieces that make React tick:
- JSX â the syntax that lets you write UIâlike markup inside JavaScript.
- Functional components â the building blocks of modern React.
- Props â the readâonly data that flows from parent to child.
- Reusability & composition â how to stitch components together for killer apps.
Weâll demystify JSX, compare it to vanilla JS, share best practices, give liveâcode examples (compatible with the Vite setup from DayâŻ3), highlight common pitfalls, and visualize key flows with diagrams. Realâworld scenarios illustrate each concept in action. By the end youâll be crafting UIs like a seasoned dev. Letâs componentâize!
đŚ JSX (JavaScriptâŻXML)
JSX is Reactâs syntax extension that lets you write HTMLâlike code directly inside JavaScript. It isnât real HTMLâBabel transpiles it into
React.createElementcalls.
Why JSX Matters
- Blends markup and logic seamlessly.
- Improves readability and maintainability vs. manual DOM manipulation.
Behind the Scenes
- Write JSX â
- Babel transpiles to plain JavaScript (
React.createElement). - React uses those element objects to build the virtual DOM.
Live Example
// JSX
const element = <h1>Hello, React!</h1>;
Transpiled version:
// JavaScript after Babel
const element = React.createElement('h1', null, 'Hello, React!');
Rendering in a component
import React from 'react';
function App() {
return <h1>Hello, React!</h1>;
}
Paste this into
src/App.jsx(orApp.tsx) and runnpm run dev. The heading appears instantly.
JSX vs. Plain JavaScript
| JSX | Plain JavaScript |
|---|---|
{message} | React.createElement('div', null, message) |
| Concise, HTMLâfamiliar | Verbose, harder to visualize nested structures |
Bottom line: JSX is just syntactic sugar; browsers ultimately see the JavaScript version.
Diagram â JSX Transpilation Process
JSX code
â
âź (Babel)
React.createElement calls
â
âź (React runtime)
Virtual DOM â Real DOM
Best Practices
- Component names â PascalCase (
MyComponent). - Selfâclosing tags â
<Component />. - Multiâline returns â wrap in parentheses:
return (âŚ);. - Prefer CSS classes over inlineâstyle objects (use inline styles only when necessary).
Common Mistake
Treating JSX like a string and concatenating it. JSX produces objects, so compose UI with components instead of string concatenation.
RealâWorld Scenario
In a blog app, a post preview is rendered with:
// Example placeholder â insert actual JSX for a post preview here
JSX lets you mix data (post.title) and structure (<h2>{post.title}</h2>) effortlessly.
âď¸ Functional Components
Functional components are plain JavaScript (or TypeScript) functions that return JSX. Since ReactâŻ16.8 (Hooks), theyâre the default choice, replacing most class components.
Why Functional?
- Simpler syntax, no
thisbinding. - Pair perfectly with Hooks for state, sideâeffects, context, etc.
Live Example
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return <Welcome name="Sara" />;
}
Renders âHello,âŻSara!â.
Structuring Tips
- Keep components small â one UI concern per component (Single Responsibility Principle).
- One file per component â
export defaultthe component. - Use arrow functions for brevity:
const Button = () => <button>Click</button>;
- Folder layout (scalable):
src/
ââ components/
ââ Button/
ââ index.jsx
ââ styles.module.css
Common Mistake
Returning multiple sibling elements without a wrapper. Fix with Fragments:
return (
<>
<div>One</div>
<div>Two</div>
</>
);
RealâWorld Scenario
A ProductCard functional component displays an itemâs image, name, price, and âAdd to Cartâ button. The same component is reused across product grids, search results, and recommendation carousels.
đ¤ Props (Properties)
Props are readâonly data passed from a parent component to a child, similar to function arguments. They enable dynamic, reusable UI.
How Props Work
// Parent â Child
<Child name="Alice" age={30} />
// Child receives them
function Child(props) {
return (
<p>{props.name} is {props.age} years old.</p>
);
}
Live Example
function Greeting(props) {
return (
<p>Hi, {props.name}! You are {props.age} years old.</p>
);
}
function App() {
return (
<>
<Greeting name="Bob" age={25} />
<Greeting name="Carol" age={28} />
</>
);
}
Two personalized greetings appear. Props flow oneâway (parent â child).
Common Pitfalls
| Issue | Why itâs a problem | Fix |
|---|---|---|
Mutating props (props.name = 'New') | Breaks immutability, no reârender. | Use state for mutable data. |
| Missing defaults | Leads to undefined values. | Provide defaultProps or destructure with defaults: function Comp({ name = 'Guest' }) { ⌠}. |
No key in lists | React canât track items efficiently. | Add a unique key prop: <Item key={id} />. |
| Prop drilling (passing through many layers) | Hard to maintain. | Use Context or a stateâmanagement library. |
Visualizing Props Flow
Parent Component
â passes props
âź
Child Component (receives props)
â may pass further down
âź
Grandchild âŚ
RealâWorld Scenario
In a socialâmedia feed, a Post component receives:
<Post author={user} content={text} timestamp={date} />
The component renders each post without hardâcoding any data.
đ Reusability
Reusability means writing a component once and using it everywhere with different props or configurations.
How to Achieve It
- Design components to accept generic props.
- Keep internal logic independent of specific data.
Live Example â Reusable Button
function Button({ label, color, onClick }) {
return (
<button style={{ backgroundColor: color }} onClick={onClick}>
{label}
</button>
);
}
function App() {
return (
<>
<Button label="Submit" color="green" onClick={() => alert('Submitted!')} />
<Button label="Cancel" color="red" onClick={() => alert('Canceled!')} />
</>
);
}
One component, two distinct behaviors â DRY and flexible.
Best Practices
- Make optional props truly optional (provide sensible defaults).
- Use TypeScript or
prop-typesto enforce prop shapes and catch errors early.
RealâWorld Scenario
A Chart component in a dashboard receives:
<Chart type="line" data={salesData} options={chartOptions} />
The same component renders different visualizations without duplication.
đ§Š Composition
Composition is the art of nesting components to build complex UIs from simple, reusable pieces. The special children prop enables flexible âslotsâ.
How It Works
- Parent wraps children in JSX.
- Child renders them via
{props.children}.
Live Example â Card Composition
function Card({ children }) {
return <div className="card">{children}</div>;
}
function App() {
return (
<Card>
<h2>Product Title</h2>
<p>Short description of the product.</p>
<button>Add to cart</button>
</Card>
);
}
Cardprovides the layout; the caller decides the inner content.
Benefits
- Separation of concerns â layout vs. content.
- Extensibility â swap out any child without touching the parent.
â TL;DR Checklist
- â
Use JSX for readable markup; remember it compiles to
React.createElement. - â Write functional components; keep them small and focused.
- â Pass props readâonly from parent â child; avoid mutating them.
- â Design components for reusability â generic props, TypeScript/propâtypes.
- â
Leverage composition (
children) to build flexible UI structures.
Now go ahead, create a tiny UI with a reusable Button, a Card wrapper, and a couple of Greeting componentsâjust like the examples above. Happy coding! đ
Component Example
function Card(props) {
return (
<div className="card">
<h2>{props.title}</h2>
{props.children}
</div>
);
}
function App() {
return (
<Card title="Profile">
<p>Name: Dana</p>
<p>Job: Developer</p>
</Card>
);
}
The Card component composes arbitrary content. You can nest deeper for hierarchies.
Best Practices
- Favor composition over inheritance â React encourages building UI by combining small, reusable components rather than relying on classâbased inheritance.
- Keep nesting logical â If a component tree becomes too deep, consider refactoring into smaller, focused components.
RealâWorld Scenario
In a news app, an Article component might be composed of:
HeaderBodyComments
Each section is reusable across different stories, while the Article component allows custom inner content (e.g., different layouts, ads, or related links).
Recap & Next Steps
- Youâve mastered JSX, functional components, props, and the art of reuse/composition â the core of scalable React apps.
- Try it yourself: Build a mini profile page using the
Cardpattern above. - Common theme: Keep your UI declarative and modular.
- Stuck on a mistake? Debug with React DevTools.
Next up: DayâŻ3 â State and Lifecycle!
Whatâs your favorite example so far? Keep building! đ