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.

CSS classes use class:

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

Form labels use for:

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

Adding JavaScript to JSX

Curly braces {} 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. Inline styles accept 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 start with a capital letter, which is how Retend tells them apart from regular HTML tags.

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

The component is used as a JSX element:

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

Passing Data with Props

Data is passed to a component with props (short for properties). Props use JSX attribute syntax:

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

Inside the component, props arrive 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>
  );
}