React React JS

Build component-based interfaces with props, state, effects, forms, routing, and API data.

React JSX Intro

React JS Lesson 18 of 66 ~9 min read

Overview

Understand JSX as JavaScript syntax that describes UI.

React JSX Intro is easiest to learn by reading the example, changing it, and observing the result.

Core Ideas

  • Understand what React JSX Intro changes.
  • Run the example.
  • Change one value.
  • Explain the result.

Step by Step

  1. Read the React JSX Intro example.
  2. Run it.
  3. Change it.
  4. Explain it.

Beginner Explanation

React JSX Intro teaches JSX, the syntax React uses to describe UI.

JSX looks like HTML, but it is JavaScript, so attributes, expressions, conditions, and event handlers follow React rules.

Beginners should remember that JSX returns one tree and uses className, htmlFor, camelCase events, and curly braces for expressions.

Before You Start

  • Before practicing React JSX Intro, make sure you can run a React project and see browser errors in the console.
  • Start with one component and one piece of data before adding routing, forms, or effects.
  • Use clear component names, such as LessonCard, LessonList, or SearchForm.
  • Change one prop, state value, or event handler at a time so the result is easy to understand.
  • Keep React examples focused on UI behavior; move repeated logic into helper functions or custom hooks later.

Key React Concepts

  • JSX expressions use curly braces.
  • Use className instead of class.
  • Use camelCase event names such as onClick and onChange.
  • A component must return one JSX tree.

Plain-English Glossary

  • Component: a reusable UI function or class.
  • JSX: JavaScript syntax that describes UI.
  • Props: read-only inputs passed from parent to child.
  • State: data owned by a component that can change over time.
  • Render: React calling components to produce UI.
  • Hook: a function such as useState or useEffect that connects components to React features.
  • Key: a stable value that identifies items in a list.
  • Effect: code that synchronizes React with something outside rendering.

What You Will Learn

  • Explain where React JSX Intro fits in a React component tree.
  • Write a small React example that uses clear props, state, JSX, or hooks.
  • Identify which component owns the data and which component only displays it.
  • Name one mistake that could cause confusing renders, broken forms, stale effects, or hard-to-maintain code.

Where You Use This in Real Projects

You use React JSX Intro in dashboards, forms, search pages, navigation, modals, carts, profile screens, admin tools, quizzes, API-driven lists, and reusable design systems.

React is valuable because it makes the UI a function of data: when props or state change, the visible interface updates.

A reliable React workflow is: design the component tree, decide state ownership, pass props down, handle events up, render lists with keys, and test loading, empty, success, and error states.

React Safety Notes

  • Do not mutate state arrays or objects directly; create new copies instead.
  • Never put hooks inside loops, conditions, nested functions, or early returns.
  • Escape and sanitize content before using dangerous HTML rendering patterns.
  • Clean up timers, subscriptions, and async work in effects when needed.
  • Keep forms accessible with labels, error messages, focus behavior, and keyboard-friendly controls.

Beginner Mental Model

Think of React JSX Intro as one piece of a component tree.

Data flows down through props, events flow up through callback props, and state changes cause React to render again.

When a React feature feels confusing, ask: what changed, who owns that value, and which components need to see it?

Code Example

const lesson = {
  title: 'React JSX',
  complete: false,
};

export default function LessonHeader() {
  return <h1 className="title">{lesson.title}: {lesson.complete ? 'Done' : 'Start'}</h1>;
}

Another Example

const user = { name: 'Asha', complete: false };

export default function WelcomeBanner() {
  return (
    <section className="banner">
      <h1>Hello {user.name}</h1>
      <p>{user.complete ? 'Ready to review' : 'Start your first lesson'}</p>
    </section>
  );
}

More Practice Examples

Example 1: Render a list with keys

const lessons = [
  { id: 1, title: 'JSX' },
  { id: 2, title: 'Props' },
];

export default function Lessons() {
  return lessons.map(lesson => <p key={lesson.id}>{lesson.title}</p>);
}
  • map turns data into UI.
  • key helps React track each item.
  • Use stable ids when possible.

Example 2: Lift state through a callback

function CounterButton({ onCount }) {
  return <button onClick={onCount}>Add</button>;
}

export default function Counter() {
  const [count, setCount] = useState(0);
  return <CounterButton onCount={() => setCount(count + 1)} />;
}
  • The parent owns the state.
  • The child receives a callback prop.
  • The click changes state in the owner component.

Example 3: Show conditional UI

export default function StatusMessage({ loading, error }) {
  if (loading) return <p>Loading...</p>;
  if (error) return <p role="alert">{error}</p>;

  return <p>Ready.</p>;
}
  • Early returns keep conditions easy to read.
  • role="alert" helps announce important errors.
  • The success UI appears only after loading and error states are handled.

Real-World Component Pattern

import { useEffect, useState } from 'react';

export default function LessonSearch() {
  const [query, setQuery] = useState('');
  const [lessons, setLessons] = useState([]);
  const [status, setStatus] = useState('idle');

  useEffect(() => {
    if (query.trim() === '') {
      setLessons([]);
      setStatus('idle');
      return;
    }

    setStatus('loading');
    fetch(`/api/lessons?q=${encodeURIComponent(query)}`)
      .then(response => response.json())
      .then(data => {
        setLessons(data);
        setStatus('success');
      })
      .catch(() => setStatus('error'));
  }, [query]);

  return <input value={query} onChange={event => setQuery(event.target.value)} />;
}
  • This React JSX Intro pattern combines state, input, effects, async loading, and conditional status.
  • The query state owns what the user typed, and the effect reacts when that value changes.
  • Real projects should also handle cancellation, empty results, accessible messages, and server errors.

Example Explained

  • The React JSX Intro example starts with data, props, or state that the component needs.
  • The component returns JSX that describes what should appear on the screen.
  • Events or effects update state, and React renders the component again.
  • Lists use keys so React can track items between renders.
  • Forms, effects, and async examples include loading, error, or submit behavior so the UI does not feel mysterious.

How to Read This Example

  1. Find the component name and its props first.
  2. Find state values and event handlers next.
  3. Read JSX from top to bottom and note which parts are conditional.
  4. Check arrays for stable keys and forms for value plus onChange.
  5. For React JSX Intro, change one prop or state value and predict the rendered output.

Checklist

  • Read the example and change one value.
  • Check the result in the browser.
  • Write down the rule you learned.

Common Mistakes

  • Skipping the example.
  • Changing many things at once.
  • Not checking the result.

Do and Don't

  • Do: practice React JSX Intro with one small component before adding a full app.
  • Do: keep state as close as possible to the components that need it.
  • Do: use stable keys, controlled inputs, clear props, and accessible labels.
  • Don't: mutate state directly or call hooks conditionally.
  • Don't: hide important loading, empty, error, and validation states from users.

Practice Challenge

Practice the React JSX Intro example in a small scratch file, then explain what changed and why.

Try These Changes

  • Add one prop and show it in JSX.
  • Add one state value and change it from a button or input.
  • Render three items with map and stable keys.
  • Add a loading or error condition before the normal UI.
  • For React JSX Intro, split one repeated part into a smaller component.

Quick Check

  • Question: What is a component? Answer: A reusable UI function or class.
  • Question: What are props? Answer: Read-only inputs passed from parent to child.
  • Question: What changes cause React to render again? Answer: State changes, prop changes, and parent renders.
  • Question: Where can hooks be called? Answer: At the top level of function components or custom hooks.
  • Question: What should you identify first in React JSX Intro? Answer: The component, its inputs, and the state it owns.

Debugging Checks

  • Read the first browser console error before changing code.
  • Check component names start with uppercase letters.
  • Check JSX attributes such as className, htmlFor, onClick, value, and checked.
  • Check effect dependency arrays when data looks stale or effects run too often.
  • Use React DevTools to inspect props, state, and component nesting.

Mini Project

Build a JSX profile card for React JSX Intro: expressions, attributes, conditional text, className, accessible labels, and one extracted variable.

Mastery Check

  • You can explain React JSX Intro.
  • You can change the example.
  • You can debug the result.
Create a free account to save which lessons you've finished. Save my progress