01 - 03 : Introduction to React.js/NEXT

ยท

4 min read

Installation

npx create-next-app

cd project-name
npm run dev

Topic 4: Props and State

4.1 Props (Properties):

  1. Inputs to React components passed from parent to child.

  2. Immutable and accessed via props in functional components or this.props in class components.

  3. Facilitate component customization and reusability.

  4. Example: <ChildComponent name="John" age={30} />.

// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
  return <ChildComponent name="John" age={30} />;
}

export default ParentComponent;
// ChildComponent.js
import React from 'react';

function ChildComponent(props) {
  return (
    <div>
      <p>Name: {props.name}</p>
      <p>Age: {props.age}</p>
    </div>
  );
}

export default ChildComponent;

State:

  • State represents the internal data of a component.

  • Unlike props, state is mutable and can be updated using the setState method.

  • State is managed within the component itself and can be modified based on user interactions, lifecycle events, or asynchronous operations.

  • State changes trigger re-renders of the component, updating the UI based on the new state.

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

export default Counter;

Topic 6: Handling Events

Basic Steps for Handling Events:

  1. Define Event Handlers:

    • Create functions to handle the desired events. These functions typically accept an event object as an argument.
  2. Attach Event Handlers:

    • Attach the event handlers to the corresponding DOM elements within your JSX using JSX syntax.

Example of Handling Click Events:

import React from 'react';

function ButtonClickExample() {
  // Event handler function
  const handleClick = () => {
    console.log('Button clicked!');
  };

  return (
    <div>
      {/* Attaching event handler to the button */}
      <button onClick={handleClick}>Click me</button>
    </div>
  );
}
export default ButtonClickExample;

Passing Arguments to Event Handlers:

You can also pass additional arguments to event handler functions by defining a wrapper function:

import React from 'react';

function ExampleWithArgument() {
  // Event handler function with argument
  const handleClick = (name) => {
    event.preventDefault(); // Prevents form submission
    console.log(`Hello, ${name}!`);
  };

  return (
    <div>
      {/* Attaching event handler with argument */}
      <button onClick={() => handleClick('John')}>Say Hello</button>
    </div>
  );
}

export default ExampleWithArgument;

Topic 7: Lists and Keys

Lists in React:

  • Represent dynamic arrays of data for rendering repetitive elements.

  • Commonly used for displaying items in shopping lists, posts in feeds, or options in dropdown menus.

  • Created by mapping over arrays and generating React elements for each item.

Keys:

  • Special attributes in React used to identify unique elements in lists.

  • Aid React in efficiently updating lists by identifying changes, additions, or removals.

  • Keys must be unique among siblings of the same parent element.

  • Specified as a special attribute (key) on elements created within a list.

Example of Rendering a List with Keys:

import React from 'react';

function ListExample() {
  const items = ['Apple', 'Banana', 'Orange'];

  return (
    <ul>
      {items.map((item, index) => (
        <li key={index}>{item}</li>
      ))}
    </ul>
  );
}

export default ListExample;

Notes:

  • It's recommended to use a unique identifier (like an ID from your data) as the key whenever possible instead of the index.

  • Avoid using indexes as keys if the list can be reordered or modified, as it can cause issues with React's reconciliation process.

  • Keys should be stable, predictable, and unique to ensure proper rendering and performance.

Topic 8: Forms and Controlled Components

import React, { useState } from 'react';

function FormExample() {
  const [inputValue, setInputValue] = useState('');

  // Event handler to update state on input change
  const handleChange = (event) => {
    setInputValue(event.target.value);
  };

  // Event handler to submit form
  const handleSubmit = (event) => {
    event.preventDefault();
    console.log('Submitted value:', inputValue);
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* Controlled input */}
      <input
        type="text"
        value={inputValue}
        onChange={handleChange}
        placeholder="Enter your name"
      />
      <button type="submit">Submit</button>
    </form>
  );
}

export default FormExample;

Topic 9: Conditional Rendering

import React from 'react';

function ConditionalRenderingExample({ isLoggedIn }) {
  return (
    <div>
      {/* ๐ŸŽฏโญ Using if-else */}
      {isLoggedIn ? (
        <p>Welcome, User!</p>
      ) : (
        <p>Please log in.</p>
      )}

      {/* ๐ŸŽฏโญ Using ternary operator */}
      {isLoggedIn ? <p>Welcome, User!</p> : <p>Please log in.</p>}

      {/* ๐ŸŽฏโญ Using logical && operator */}
      {isLoggedIn && <p>Welcome, User!</p>}
    </div>
  );
}

export default ConditionalRenderingExample;
ย