JSX and Components

Retend uses JSX to describe user interfaces and components to organize JSX into reusable pieces.

What is JSX?

JSX uses HTML-like syntax in JavaScript or TypeScript files. It allows markup and related logic to be defined together.

const heading = <h1>Hello, Retend!</h1>;

JSX supports standard HTML attributes.

For CSS classes, use class:

<div class="card-container">
  <p class="text-large">Welcome</p>
</div>

For form labels, use for:

<label for="username">Username</label>
<input type="text" id="username" />

Adding JavaScript to JSX

Use curly braces {} to insert JavaScript expressions into JSX.

const userName = 'Alice';
const userAge = 28;

const profile = (
  <div class="profile">
    <h2>{userName}</h2>
    <p>Age: {userAge}</p>
  </div>
);

Curly braces also work for attributes. For inline styles, pass a JavaScript object:

const alertBox = (
  <div style={{ backgroundColor: 'red', color: 'white' }}>
    Something went wrong!
  </div>
);

What are Components?

Components separate an interface into smaller units. This helps organize JSX as an application grows.

A Retend component is a JavaScript function that returns JSX. Component names must start with a capital letter so Retend can tell them apart from regular HTML tags.

function Greeting() {
  return <div>Welcome to our application!</div>;
}

Use the component as a JSX element:

function App() {
  return (
    <main>
      <h1>Home Page</h1>
      <Greeting />
    </main>
  );
}

Passing Data with Props

Pass data to a component with props (short for properties). Props use JSX attribute syntax:

<UserCard name="Alice" age={30} />

Inside your component, you receive these props as a single object.

function UserCard(props) {
  const { name, age } = props;

  return (
    <div class="card">
      <h3>{name}</h3>
      <p>Age: {age}</p>
    </div>
  );
}

Wrapping Content with Children

A component can receive nested content through the children prop. Content between its opening and closing tags is passed as children:

function AlertBox(props) {
  const { children } = props;

  return <div class="alert-box">{children}</div>;
}

function App() {
  return (
    <AlertBox>
      <strong>Warning!</strong> Please check your inputs.
    </AlertBox>
  );
}