DEV Community

Cover image for Building with React: Dive into JSX, Components, and Props! (React Day 2)
Vasu Ghanta
Vasu Ghanta

Posted on

Building with React: Dive into JSX, Components, and Props! (React Day 2)

Hey, React rookies-turned-pros! Welcome back from Day 1, where we unpacked React's big picture. Today, we're zooming in on the essentials that make React tick: JSX for writing UI, functional components as your building blocks, props for data flow, and how to reuse and compose them for killer apps. We'll demystify JSX's inner workings, compare it to vanilla JS, share best practices, drop code examples you can "live" test in your setup (like Vite from Day 3), highlight pitfalls, and visualize key flows. Plus, real-world scenarios to see it all in action. By the end, you'll craft UIs like a seasoned dev. Let's component-ize!

JSX: The Syntax That Makes React Shine

JSX (JavaScript XML) is React's way of letting you write HTML-like code right inside JavaScript. It's not actual HTML—it's a syntax extension that makes declaring UIs feel natural and expressive.

Why It Matters: JSX blends markup and logic seamlessly, making code more readable and maintainable than pure JS DOM manipulation.

Behind the Scenes: JSX doesn't run directly in browsers. Tools like Babel transpile it into plain JavaScript calls to React.createElement(). This function creates React elements (lightweight descriptions of UI).

Live Example: Here's JSX for a simple heading:

const element = <h1>Hello, React!</h1>;
Enter fullscreen mode Exit fullscreen mode

Transpiled behind the scenes:

const element = React.createElement('h1', null, 'Hello, React!');
Enter fullscreen mode Exit fullscreen mode

Render it in a component:

import React from 'react';

function App() {
  return <h1>Hello, React!</h1>;
}
Enter fullscreen mode Exit fullscreen mode

Paste this into your App.jsx and run npm run dev—boom, it appears!

JSX vs. Plain JavaScript Comparison:

  • JSX: Concise and HTML-familiar: <div>{message}</div>. Embed JS expressions in curly braces {}.
  • Plain JS: Verbose: React.createElement('div', null, message). Harder to visualize nested structures.

JSX wins for developer experience, but remember: It's sugar—browsers see the JS version.

Here's a diagram illustrating the JSX transpilation process:

How React.js Works Under the Hood: A Deep Dive into Its

Best Practices:

  • Use PascalCase for component names (e.g., MyComponent).
  • Close self-closing tags: <img src="..." />.
  • For multi-line, wrap in parentheses: return (<div>...</div>);.
  • Avoid inline styles as objects unless necessary—prefer CSS classes.

Common Mistake: Treating JSX like strings—it's objects! Don't concat like HTML; compose with components.

Real-World Scenario: In a blog app, JSX renders dynamic post previews: <Post title={post.title} excerpt={post.excerpt} />, mixing data and structure effortlessly.

Functional Components: The Modern Way to Build UI

Functional components are plain JavaScript functions that return JSX. They're the go-to in modern React (post-Hooks in React 16.8), replacing class components for most cases.

Why Functional? Simpler, no this binding issues, and they pair perfectly with hooks for state and effects (more on Day 3).

Live Example: A basic welcome component:

function Welcome(props) {
  return <h1>Hello, {props.name}!</h1>;
}

function App() {
  return <Welcome name="Sara" />;
}
Enter fullscreen mode Exit fullscreen mode

This renders "Hello, Sara!". Functions make components feel like reusable functions.

Best Practices for Structuring:

  • Keep components small and focused (Single Responsibility Principle)—one component per UI concern.
  • Organize files: One component per file, export default.
  • Use arrow functions for conciseness: const Button = () => <button>Click</button>;.
  • Folder structure: src/components/Button/index.jsx for scalability.

Common Mistake: Returning multiple elements without a wrapper—fix with fragments: <> <p>One</p> <p>Two</p> </>.

Real-World Scenario: In an e-commerce site, a ProductCard functional component displays item details, reusable across grids.

Props: Data Passing Made Easy

Props (short for properties) are read-only data passed from parent to child components, like function arguments. They make components dynamic and reusable.

How It Works: Parents pass props as attributes in JSX; children access via props object.

Live Example: Parent-child flow:

function Greeting(props) {
  return <p>Hi, {props.name}! You are {props.age} years old.</p>;
}

function App() {
  return (
    <div>
      <Greeting name="Alex" age={28} />
      <Greeting name="Jordan" age={32} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Output: Two personalized greetings. Props flow one-way—down the tree.

Common Mistakes with Props:

  • Mutating props: Props are immutable! Don't do props.name = 'New';—it won't re-render and breaks predictability. Use state instead.
  • Forgetting defaults: Use defaultProps or destructuring: function Greeting({ name = 'Guest' }) {...}.
  • No keys in lists: When mapping arrays, add key prop: <Item key={id} /> to help React track changes efficiently.
  • Over-passing: Avoid prop drilling (passing through many levels)—use Context for deep data.

Visualize the parent-child props data flow:

parenting in react

Real-World Scenario: In a social media feed, a Post component receives props like user, content, and likes from a parent Feed, displaying customized posts without hardcoding.

Component Reusability: Don't Repeat Yourself (DRY)

Reusability means writing a component once and using it everywhere with different props or configs. It's React's superpower for efficient code.

How to Achieve: Design components to accept varied props, making them generic.

Live Example: Reusable button:

function Button(props) {
  return <button onClick={props.onClick} style={{ background: props.color }}>{props.label}</button>;
}

function App() {
  return (
    <div>
      <Button label="Submit" color="green" onClick={() => alert('Submitted!')} />
      <Button label="Cancel" color="red" onClick={() => alert('Canceled!')} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

One component, two behaviors—DRY and flexible.

Best Practices: Make props optional where possible; use TypeScript for prop types to catch errors.

Real-World Scenario: In a dashboard app, a Chart component reuses across pages with props for data and type (bar/line), avoiding duplicate code.

Component Composition: Assembling UIs Like Puzzles

Composition is nesting components to build complex UIs from simpler ones. Use the special children prop for flexible slots.

How It Works: Parents wrap children in JSX; children render via {props.children}.

Live Example: Composed card:

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

The card composes arbitrary content. Nest deeper for hierarchies.

Here's a diagram showing component composition and reusability:

Understanding Component Structure in React: The Building Blocks of...

Best Practices: Favor composition over inheritance—React doesn't use classes like OOP. Keep nesting logical; refactor if too deep.

Real-World Scenario: In a news app, a Article component composes Header, Body, and Comments sections, reusable for different stories while allowing custom inner content.

Wrapping Up: Your React Toolkit Grows

You've mastered JSX's magic, functional components' simplicity, props' flow, and the art of reuse/composition—core to scalable React apps. Try composing a mini profile page with these. Common theme? Keep it declarative and modular. Stuck on a mistake? Debug with React DevTools. Next up, Day 3: State and Lifecycle! What's your fave example so far? Keep building! 🚀

Top comments (0)