What is React?

React is a JavaScript library for building user interfaces (UIs). Think of it like a box of LEGOs. Instead of building a whole website monolithically, you build small, independent, and reusable pieces called components and then compose them together to create complex UIs.

The core philosophy of React is to be declarative. You simply "declare" what you want the UI to look like for any given state of your application, and React will efficiently update and render just the right components when your data changes.

The Core Idea: Components

A component is a self-contained piece of UI. A button, a form, a user profile card, or even an entire page can be a component. They are just JavaScript functions that return some special HTML-like code.

Let's look at a simple component:

JavaScript


// This is a React Function Component.
// It's just a JavaScript function that starts with a capital letter.
function WelcomeMessage() {
  // It returns what looks like HTML. This is JSX.
  return <h1>Hello, world!</h1>;
}

You can then use this component elsewhere in your application, just like a custom HTML tag: <WelcomeMessage />. This reusability is what makes React so powerful.

What is JSX?

The HTML-like syntax you see above is called JSX (JavaScript XML). It's a syntax extension for JavaScript that lets you write your UI structure in a familiar way.

Important: JSX is NOT HTML. Your browser doesn't understand JSX directly. Before your code runs in the browser, a tool like Babel compiles your JSX into regular React.createElement() function calls, which are plain JavaScript objects that React knows how to turn into DOM elements.

JavaScript


// This JSX:
const element = <h1 className="greeting">Hello!</h1>;

// Gets compiled into this JavaScript:
const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello!'
);

You don't need to worry about the compiled output, but it's helpful to know that under the hood, it's just JavaScript!

The Rules of JSX

JSX is mostly intuitive, but there are a few key rules to remember:

  1. Return a Single Root Element: A component can only return one top-level element. If you need to return multiple elements, wrap them in a container like a <div> or, even better, a Fragment (<>...</>).

JavaScript

// GOOD: Wrapped in a Fragment
function UserProfile() {
  return (
    <>
      <h2>Alice</h2>
      <p>Software Engineer</p>
    </>
  );
}
  1. Use className instead of class: Since class is a reserved keyword in JavaScript, JSX uses className to specify a CSS class.
  2. Use camelCase for Attributes: HTML attributes like onclick or tabindex become onClick and tabIndex in JSX.
  3. Embed Expressions with Curly Braces {}: You can embed any valid JavaScript expression inside JSX by wrapping it in curly braces.


function Greeting() {
  const name = "Alice";
  return <h1>Hello, {name.toUpperCase()}! You have {2 + 3} messages.</h1>;
}