You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// JSX is React's syntax extension for JavaScript// It allows you to write HTML-like code in JavaScript// Basic JSX - Simple element creationconstelement=<h1>Hello, React!</h1>;// JSX with JavaScript Expressions - Use curly braces {} to embed JavaScriptconstname='User';constgreeting=<h1>Hello, {name}!</h1>;// Will display: Hello, User!// JSX Attributes - Use className instead of class for CSS classesconstbutton=<buttonclassName="btn">Click me</button>;// Multi-line JSX - Must be wrapped in parentheses// This creates a nested structure of elementsconstcontainer=(<div><h1>Title</h1><p>Content</p></div>);
Components
// Components are reusable pieces of UI// They can be created in several ways:// Function Component - The simplest way to create a component// Takes props as an argument and returns React elementsfunctionWelcome(props){return<h1>Hello, {props.name}</h1>;}// Arrow Function Component - Modern alternative syntax// Functionally identical to regular function componentsconstWelcome=(props)=>{return<h1>Hello, {props.name}</h1>;};// Class Component - Traditional way to create components// Provides additional features like lifecycle methodsclassWelcomeextendsReact.Component{render(){return<h1>Hello, {this.props.name}</h1>;}}// Using Components - Components can be nested and reused// Each component instance can receive different propsconstelement=(<div><Welcomename="Alice"/>{/* Renders: Hello, Alice */}<Welcomename="Bob"/>{/* Renders: Hello, Bob */}</div>);
Props
// Props (properties) are how components receive data// They are read-only and help make components reusable// Basic Props - Passing data to a componentfunctionGreeting(props){return<h1>Hello, {props.name}!</h1>;}// Props with Destructuring - Cleaner way to access props// Directly extract the values you needfunctionGreeting({ name, age }){return(<div><h1>Hello, {name}!</h1><p>Age: {age}</p></div>);}// Default Props - Fallback values if props aren't providedfunctionGreeting({ name ='Guest'}){return<h1>Hello, {name}!</h1>;// Uses 'Guest' if name prop is missing}// Children Props - Special prop for nested content// Allows components to wrap other elementsfunctionContainer({ children }){return<divclassName="container">{children}</div>;}
State
// State manages data that can change over time// When state updates, React re-renders the component// useState Hook - Most common way to manage state// Returns current state and a function to update itfunctionCounter(){const[count,setCount]=useState(0);// [currentValue, updateFunction]return(<div><p>Count: {count}</p><buttononClick={()=>setCount(count+1)}>
Increment
</button></div>);}// Multiple State Values - Components can have multiple states// Each useState call manages an independent piece of statefunctionUserForm(){const[name,setName]=useState('');// State for name inputconst[age,setAge]=useState(0);// State for age inputreturn(<form><inputvalue={name}onChange={(e)=>setName(e.target.value)}/><inputtype="number"value={age}onChange={(e)=>setAge(Number(e.target.value))}/></form>);}
Events
// React events handle user interactions// They use camelCase naming (onClick, onChange, etc.)// Event Handling - Basic click eventfunctionButton(){consthandleClick=()=>{console.log('Button clicked!');};return<buttononClick={handleClick}>Click Me</button>;}// Event with Parameters - Passing additional data to event handlersfunctionButton({ id }){consthandleClick=(event,id)=>{console.log(`Button ${id} clicked!`,event);// event contains information about the event};return(<buttononClick={(e)=>handleClick(e,id)}>
Click Me
</button>);}// Form Events - Handling form submissionsfunctionForm(){consthandleSubmit=(event)=>{event.preventDefault();// Prevents page reload// Form handling logic here};return(<formonSubmit={handleSubmit}><buttontype="submit">Submit</button></form>);}
Lists & Keys
// React needs keys to efficiently update lists// Keys help React identify which items changed// Rendering Lists - Basic list rendering with keysfunctionItemList({ items }){return(<ul>{items.map(item=>(// key prop helps React track each item<likey={item.id}>{item.name}</li>))}</ul>);}// Complex List Items - Rendering lists with more structurefunctionUserList({ users }){return(<div>{users.map(user=>(// Each top-level element in map needs a key<divkey={user.id}className="user-card"><h3>{user.name}</h3><p>{user.email}</p></div>))}</div>);}
Conditional Rendering
// Conditional rendering shows different content based on conditions// If Statement - Basic conditional renderingfunctionGreeting({ isLoggedIn }){if(isLoggedIn){return<h1>Welcome back!</h1>;}return<h1>Please log in</h1>;}// Ternary Operator - Inline conditional rendering// Shorter syntax for simple conditionsfunctionGreeting({ isLoggedIn }){return(<div>{isLoggedIn ? (<h1>Welcome back!</h1>) : (<h1>Please log in</h1>)}</div>);}// Logical && Operator - Conditional rendering for single outcomes// Shows element only if condition is truefunctionNotification({ message }){return(<div>{message&&<p>{message}</p>} // Shows message only if it exists
</div>);}
Forms
// React forms use controlled components to manage form data// Form elements are controlled by React state// Controlled Component - React manages form datafunctionLoginForm(){// State for each form fieldconst[username,setUsername]=useState('');const[password,setPassword]=useState('');consthandleSubmit=(e)=>{e.preventDefault();// Prevent default form submissionconsole.log('Submit:',{ username, password });};return(<formonSubmit={handleSubmit}><inputtype="text"value={username}// Value controlled by stateonChange={(e)=>setUsername(e.target.value)}// Update state on change/><inputtype="password"value={password}onChange={(e)=>setPassword(e.target.value)}/><buttontype="submit">Login</button></form>);}// Multiple Input Handler - Managing multiple inputs efficientlyfunctionSignupForm(){// Single state object for all form fieldsconst[values,setValues]=useState({username: '',email: '',password: ''});// Generic handler for all inputsconsthandleChange=(e)=>{const{ name, value }=e.target;setValues(prev=>({
...prev,// Spread existing values[name]: value// Update only changed field}));};return(<form><inputname="username"// name attribute matches state propertyvalue={values.username}onChange={handleChange}/><inputname="email"type="email"value={values.email}onChange={handleChange}/><inputname="password"type="password"value={values.password}onChange={handleChange}/></form>);}