React Components and JSX

Master modern React function components, declarative JSX markup, fragment grouping, and expression embedding syntax.

TL;DR

  1. Declare reusable user interface blocks using standard function components.
  2. Return declarative JSX markup with camelCase properties and embedded expressions.
  3. Group adjacent sibling tags cleanly using <> empty Fragment wrappers.

Component Declarations

    Function Component

    Standard function returning declarative JSX tree markup.

    export function Welcome() {
      return <Header>Hello React World</Header>;
    }
    Arrow Component

    Arrow function syntax assigned to a typed constant.

    export const Card = () => (
      <CardView className="card">Content</CardView>
    );
    Fragment Wrapper

    Empty tags prevent redundant DOM wrapper elements.

    return (
      <>
        <Header>Title</Header>
        <Subtitle>Subtitle</Subtitle>
      </>
    );

JSX Embedding

    Variable Embedding

    Embed dynamic JavaScript expressions with curly braces.

    const user = 'Taylor';
    return <Header>Welcome, {user}!</Header>;
    Attribute Binding

    Pass dynamic strings or objects into HTML attributes.

    const avatar = '/img/u1.png';
    return <CardMedia src={avatar} alt="Avatar" />;
    Inline Style Object

    Apply camelCase styling properties using double braces.

    return (
      <Box style={{ color: 'navy', padding: 8 }}>
        Styled Text
      </Box>
    );

JSX Attributes

    CSS Class Name

    Use className instead of the reserved class keyword.

    <Button className="btn-primary">
      Submit
    </Button>
    Form Label Target

    Use htmlFor instead of for for accessible form labels.

    <Label htmlFor="email-id">
      Email Address
    </Label>
    Boolean Attributes

    Pass booleans directly or omit value for true.

    <Input type="text" disabled readOnly />

Nesting and Composition

    Nested Tags

    Place custom components directly inside parent JSX trees.

    export function App() {
      return (
        <Layout>
          <Welcome />
          <Card />
        </Layout>
      );
    }
    Self-Closing Tags

    Always self-close tags that do not have nested children.

    <Input type="search" />
    <Divider />
    <Image src="/hero.jpg" alt="Hero" />
    Keyed Fragment

    Use explicit Fragment import when attaching key props.

    import { Fragment } from 'react';
    return <Fragment key={id}>item</Fragment>;

Tips

  1. Always capitalize custom component names so React distinguishes them from native lowercase HTML elements during compilation.
  2. Keep component functions pure by avoiding side effects inside the return statement during UI rendering.

Warnings

  1. Never return multiple root elements without wrapping them inside a <Fragment> or empty tag <> container.
  2. Remember that class and for are reserved words, requiring className and htmlFor in JSX.

In Practice

FAQ