React Basics

Introduction to React Basics

React is a declarative, component-based JavaScript library for building interactive user interfaces. It leverages a virtual DOM to efficiently update UI on data changes.

You'll learn core concepts: JSX, components, props, state, event handling, and rendering lists.

JSX Syntax

JSX lets you write HTML-like code within JavaScript:

// Hello.js
function Hello() {
  return <h1>Hello, React!</h1>;
}
export default Hello; 

JSX expressions must have a single parent element, and you can embed JS with curly braces: {expression}.

Components & Props

Components are reusable building blocks. Props pass data into components:

function Greeting({ name }) {
  return <p>Hello, {name}!</p>;
}

// Usage:
<Greeting name="Rohan" /> 

State & Hooks

State stores dynamic data in functional components using the useState hook:

import { useState } from 'react';
function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(c => c + 1)}>Click me</button>
    </div>
  );
} 

Event Handling

React events use camelCase and pass event handlers directly:

function Form() {
  function handleSubmit(e) {
    e.preventDefault();
    alert('Form submitted');
  }
  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">Submit</button>
    </form>
  );
} 

Conditional Rendering

Render elements based on conditions:

function UserStatus({ isLoggedIn }) {
  return isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>;
} 

Lists & Keys

Render lists with map and provide a unique key for each item:

function NumberList({ numbers }) {
  return (
    <ul>
      {numbers.map(n => <li key={n}>{n}</li>)}
    </ul>
  );
}

<NumberList numbers={[1,2,3]} /> 

Forms & Controlled Components

Use state to control form inputs:

function NameForm() {
  const [name, setName] = useState('');
  return (
    <form onSubmit={e => e.preventDefault()}>
      <input value={name} onChange={e => setName(e.target.value)} />
      <button type="submit">Submit</button>
    </form>
  );
}