Examples (Components and States) - anastasiamexa/react-complete-guide-course-resources GitHub Wiki

Working with Components

import keyConceptsImage from '../assets/images/key-concepts.png';

function Header(props) {
  return (
    <header>
      <img src={keyConceptsImage} alt="Medal badge with a star" />
      <h1>{props.title}</h1>
      <p>{props.desc}</p>
    </header>
  );
}

export default Header;

This React code defines a functional component called Header. Functional components in React are JavaScript functions that return JSX (JavaScript XML) elements, which describe the structure and content of a UI component. This component takes in props as an argument and returns JSX to describe the structure of a header section in a React application. Let's break down the code step by step:

1. Importing an Image:
This line imports an image named keyConceptsImage from the '../assets/images/key-concepts.png' file. This image can be used within the Header component as the source (src) for an <img> element. Similarly, other assets or event components can be imported, to be used by the Header component.

2. Function Declaration:

function Header(props) {

Here, a function named Header is declared. It takes a single argument props, which is an object containing properties passed to the component.

3. Component Rendering:
Inside the Header function, JSX code is used to define the structure of the header.

<header>
  <img src={keyConceptsImage} alt="Medal badge with a star" />
  <h1>{props.title}</h1>
  <p>{props.desc}</p>
</header>

Note that the syntax {props.title} and {props.desc} is used to obtain the value of props properties.

4. Component Export:

export default Header;

Finally, the Header component is exported so that it can be used in other parts of your React application.

5. Component Usage:

<Header title="React Concepts" desc="A collection of key React concepts" />

To use the component in other parts of the application (ex. App.js), all you need to do is creating an instance of the Header component and passing it two props: title and desc.

In summary, this React code defines a Header component that includes an image, a main title (<h1>), and a description (<p>) within a <header> element. Making it easy to use this component in different parts of your application.

Working with States

Example 1

import React, {useState} from 'react';

export default function App() {
    const [stateValue, setStateValue] = useState('Invalid');
    
    function msgChangeHandler(event) {
        if (event.target.value.trim().length < 3) {
          setStateValue('Invalid');
        } else {
          setStateValue('Valid');
        }
    }
    
    return (
        <form>
            <label>Your message</label>
            <input type="text" onChange={msgChangeHandler}/>
            <p>{stateValue} message</p>
        </form>
    );
}

This code demonstrates how to use the useState hook to manage and display the state of a message's validity based on the length of text entered into an input field. Here's a step-by-step explanation of the code:

  1. Import React and the useState hook from the 'react' library:
import React, { useState } from 'react';
  1. Initialize a state variable called stateValue and a function to update it called setStateValue using the useState hook. Initially, stateValue is set to 'Invalid'.
const [stateValue, setStateValue] = useState('Invalid');
  1. Create an event handler function called msgChangeHandler. This function is called whenever the user types in the input field. It checks the length of the input text and updates the stateValue accordingly. If the length is less than 3 characters, it sets stateValue to 'Invalid', otherwise, it sets it to 'Valid'.
function msgChangeHandler(event) {
    if (event.target.value.trim().length < 3) {
        setStateValue('Invalid');
    } else {
        setStateValue('Valid');
    }
}
  1. Inside the return statement, render a form element with the following components:
  • A label element: "Your message."
  • An input element of type "text" with an onChange event handler that calls msgChangeHandler when the user types into the input field.
  • A paragraph element that displays the stateValue variable, which represents the validity of the message (either 'Valid' or 'Invalid').
return (
    <form>
        <label>Your message</label>
        <input type="text" onChange={msgChangeHandler} />
        <p>{stateValue} message</p>
    </form>
);
  1. The stateValue variable is displayed inside the paragraph element, so as the user types in the input field, the paragraph will dynamically update to show whether the message is 'Valid' or 'Invalid' based on the length of the input text.

In summary, this React component maintains a simple form where the user can input text, and it provides real-time feedback on the validity of the message based on the length of the input text. If the input is less than three characters long, it is considered 'Invalid,' otherwise, it is considered 'Valid.'

Example 2

import React, {useState} from 'react';

export default function App() {
    const [counter, setCounter] = useState(0);
    
    function incrementHandler(event) {
        setCounter((prevState) => {
            return prevState + 1;
        });
    }
    
    return (
      <div>
        <p id="counter">{counter}</p>
        <button onClick={incrementHandler}>Increment</button>
      </div>
    );
}

This code demonstrates how to use the useState hook to manage and display a counter value. When the "Increment" button is clicked, the counter value is incremented by one. Here's a step-by-step explanation of the code:

  1. Import React and the useState hook from the 'react' library:
import React, { useState } from 'react';
  1. Initialize a state variable called counter and a function to update it called setCounter using the useState hook. Initially, counter is set to 0.
const [counter, setCounter] = useState(0);
  1. Create an event handler function called incrementHandler. This function is called when the "Increment" button is clicked. It uses the setCounter function to update the counter state. It takes the previous state value (prevState) as an argument and returns the updated state value by adding 1 to it.
function incrementHandler(event) {
    setCounter((prevState) => {
        return prevState + 1;
    });
}
  1. Inside the return statement, render a div element with the following components:
  • A paragraph element with the id "counter" that displays the counter variable. This will display the current counter value.
  • A button with an onClick event handler that calls the incrementHandler function when clicked. This button allows the user to increment the counter
return (
    <div>
        <p id="counter">{counter}</p>
        <button onClick={incrementHandler}>Increment</button>
    </div>
);
  1. The counter variable is displayed inside the paragraph element, so as the user clicks the "Increment" button, the counter value will increase by 1, and the updated value will be displayed.

In summary, this React component maintains a simple counter that can be incremented by clicking the "Increment" button. The current counter value is displayed on the page, and it is updated in real-time as the user interacts with the component.

⚠️ **GitHub.com Fallback** ⚠️