JavaScript & React Fundamentals
Course Overview: JavaScript & React
Course Overview: JavaScript & React
• Week 3 of our web development curriculum
• Focus on modern JavaScript (ES6+) features
• Introduction to React fundamentals
• Building functional components
• Understanding JSX syntax and usage
• Learning about props and state
JavaScript ES6+ Essentials
• ES6 (ECMAScript 2015) revolutionized JavaScript
• Modern syntax for cleaner, more readable code
• Key features we\'ll cover:
• Variable declarations: let and const
• Arrow functions
• Template literals
• Destructuring
• Spread/rest operators
• Classes and modules
Variable Declarations: let and const
• let: Block-scoped variable that can be reassigned
let count = 0; count = 1; Valid reassignment
• const: Block-scoped constant that cannot be reassigned
const API_URL = "[Link] API_URL = new-url; Error:
Assignment to constant variable
• Both solve issues with hoisting that var had
• Best practice: Use const by default, let when reassignment is needed
Arrow Functions
• Concise syntax for writing functions
• Traditional function:
function add(a, b) { return a + b; }
• Arrow function equivalent:
const add = (a, b) => a + b;
• Benefits:
• Shorter syntax
• Implicit returns for one-line functions
• Lexical this binding (inherits from parent scope)
Template Literals
• Enhanced way to work with strings
• Uses backticks (`) instead of quotes
• Allows for multi-line strings
• Enables string interpolation with ${expression}
const name = "Student"; const greeting = Hello, ${name}! Welcome to React
class.
• Useful for creating dynamic content in React
Destructuring & Spread Operator
• Destructuring: Extract values from objects and arrays
const user = { name: 'Alex', age: 25 }; const { name, age } = user; name = 'Alex',
age = 25
• Spread operator (...): Expand iterables into individual elements
const nums = [1, 2, 3]; const newNums = [...nums, 4, 5]; [1, 2, 3, 4, 5] const
userWithRole = { ...user, role: 'Admin' }; { name: 'Alex', age: 25, role: 'Admin' }
• Frequently used in React for immutable state updates
Introduction to React
• JavaScript library for building user interfaces
• Created by Facebook, released in 2013
• Component-based architecture
• Virtual DOM for efficient rendering
• Declarative approach to UI development
• Unidirectional data flow
• Large ecosystem and community support
React Components
• Building blocks of React applications
• Two types:
• Class components (older approach)
• Functional components (modern approach)
• Components can be nested and reused
• Each component manages its own logic and rendering
• Components accept "props" and can maintain "state"
Functional Components
• JavaScript functions that return React elements
• Simple syntax:
function Greeting(props) { return <h1>Hello, {[Link]}!</h1>; }
• Arrow function equivalent:
const Greeting = (props) => <h1>Hello, {[Link]}!</h1>;
• More lightweight than class components
• With hooks, can now use all React features
Functions vs. Functional Components
• Regular JavaScript functions:
• Return any value
• Called directly: add(2, 3)
• No specific structure required
• Functional components:
• Return JSX (React elements)
• Used as JSX tags: <Greeting name="Alex" />
• Follow React component naming conventions (PascalCase)
• Can receive props as parameters
• Can use React hooks
Introduction to JSX
• JavaScript XML - syntax extension for JavaScript
• Looks like HTML, but with JavaScript capabilities
• Allows writing HTML-like code in JavaScript
• Gets transformed to JavaScript by Babel
• Enables declarative UI programming
const element = <h1>Hello, world!</h1>;
• Transforms to:
const element = [Link]('h1', null, 'Hello, world!');
JSX Syntax Rules
• Must have a single root element (or fragment)
• All tags must be closed
• Attributes use camelCase naming:
• className instead of class
• onClick instead of onclick
• JavaScript expressions inside curly braces {}
• Conditional rendering with ternary operators
• Comments inside JSX: {/* comment */}
Using JSX to Render UI Elements
• Embedding expressions:
const name = 'Alex'; const element = <h1>Hello, {name}</h1>;
• Rendering lists:
const items = ['Apple', 'Banana', 'Cherry']; const listItems = [Link]((item,
index) => <li key={index}>{item}</li>); const list = <ul>{listItems}</ul>;
• Conditional rendering:
const isLoggedIn = true; const element = isLoggedIn ? <UserGreeting /> :
<GuestGreeting />;
JSX Attributes and Events
• HTML attributes become props in JSX
const element = <img src={[Link]} alt={[Link]} />;
• Event handling:
const handleClick = () => alert('Button clicked!'); const button = <button
onClick={handleClick}>Click me</button>;
• Inline styles require objects with camelCase properties:
const style = { backgroundColor: 'blue', color: 'white' }; const element = <div
style={style}>Styled content</div>;
Understanding Props
• Props = Properties passed to components
• Read-only data that flows down from parent to child
• Passed like HTML attributes:
<UserProfile name="Alex" role="Admin" />
• Accessed inside the component:
const UserProfile = (props) => { return <div>Name: {[Link]}, Role:
{[Link]}</div>; };
• Props can be destructured:
const UserProfile = ({ name, role }) => { return <div>Name: {name}, Role:
{role}</div>; };
Props Example: Component Composition
// Button component const Button = ({ text, onClick, color }) => { return ( <button
onClick={onClick} style={{ backgroundColor: color }}> {text} </button> ); }; //
Parent component using Button const App = () => { const handleClick = () =>
alert('Submitted!'); return ( <div> <h1>Form</h1> <Button text="Submit"
onClick={handleClick} color="blue" /> </div> ); };
Introduction to State
• Data that changes over time within a component
• Causes re-rendering when updated
• In functional components, managed with the useState hook
import React, { useState } from 'react'; const Counter = () => { const [count,
setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={()
=> setCount(count + 1)}> Increment </button> </div> ); };
• State updates are asynchronous
• State should be treated as immutable
State vs. Props
| Props | State | |-------|-------| | Passed from parent | Created within component
| | Read-only | Can be modified | | Cause re-render when parent updates |
Causes re-render when updated | | Can be default values | Requires initial value
| | Accessed via props object or destructuring | Accessed via state variable | |
Used for component configuration | Used for component internal data |// Props
example const Greeting = ({ name }) => <h1>Hello, {name}!</h1>; // State
example const ToggleButton = () => { const [isOn, setIsOn] = useState(false);
return ( <button onClick={() => setIsOn(!isOn)}> {isOn ? 'ON' : 'OFF'} </button> );
};
Putting It All Together: A Simple React App
import React, { useState } from 'react'; // Functional component with props const
Header = ({ title }) => <h1>{title}</h1>; // Functional component with props and
event handler const Button = ({ text, onClick }) => <button
onClick={onClick}>{text}</button>; // Main component with state const App = ()
=> { const [count, setCount] = useState(0); const increment = () =>
setCount(count + 1); const decrement = () => setCount(count - 1); const reset = ()
=> setCount(0); return ( <div> <Header title="React Counter App" /> <p>Current
count: {count}</p> <Button text="+" onClick={increment} /> <Button text="-"
onClick={decrement} /> <Button text="Reset" onClick={reset} /> </div> ); };
export default App;
Key Takeaways & Next Steps
• ES6+ features make JavaScript more powerful and expressive
• React functional components provide a clean way to build UIs
• JSX combines HTML and JavaScript for declarative programming
• Props allow component configuration and composition
• State enables interactive, dynamic applications
• Next topics to explore:
• React Hooks (useEffect, useContext, etc.)
• Managing complex state
• Component lifecycle
• Routing in React
• Working with APIs