Javascript and React - Scripts

Getting Started with React: A Simple Counter

React is a JavaScript library created by Facebook (now Meta). It is used to build interactive and dynamic user interfaces. It is well known in the web development world due to its efficiency, reusability, and maintainability.

In React, we use tags similar to HTML, but they are called JSX (JavaScript XML) elements. One of the cool things about JSX is that it allows you to write HTML-like syntax inside JavaScript, making it easier to create and manage the UI.

There are some key differences between HTML and JSX. For example, tags such as <img>, <br>, and <input> must always be self-closed with a / in JSX. Additionally, since class is a reserved keyword in JavaScript, we use className in JSX to define CSS classes.

With that said, let’s have some fun with React by creating a simple counter! You can use these tags and elements to build other components as well.

    Setting Up Your Development Environment

    Before we begin, ensure that you have the following installed:

    Creating the project

    Open your terminal and run the following command (a useful tip is to create a specific directory for your project using mkdir, which will make it easier to find and keep your workspace organized 😉):

    npx create-react-app my-app
    

    Note: the "my-app" will be the name of the project, so change if you want to. But be careful with the long names and special characters!

    Now, navigate into the project directory and start the development server:

    cd my-app
    npm start

    Your project should running!

    The Script

    Understanding the Project Structure

    As you might notice, there are many files and scripts in the newly created project. We will modify some of them to suit our needs.

    Creating a Component

    First, create a new directory inside the src folder. Here, we will name it Components. Inside this folder, create another folder called Member, which will contain a file named index.js. Below is the script:

    import React, { Component } from 'react';
    
    class Member extends Component{
        render(){
            return(
                <div>
                    Member
                </div>
            );
        }
    }
    
    export default Member;

    Modifying App.js

    Next, we modify the App.js file to implement our counter:

    //impost react and component to create a class based.
    import React, { Component } from 'react'; 
    //App inherits the functionality from Component.
    class App extends Component {
    
      constructor(props) {
    //super props is the parent constructor, and you can only use this after calling the super(props).
        super(props);
    //initializes the component state as a counter set to 0
        this.state = {
          counter: 0
        };
    
    //increase and decrease are bound to the class context using bind. This is necessary so that the methods maintain access to this when used as event callbacks.
        this.increase = this.increase.bind(this);
        this.decrease = this.decrease.bind(this);
      }
    //increase the value by 1
      increase() {
        let state = this.state;
        state.counter += 1;
    //update state and trigger new rendering
        this.setState(state);
      }
    //decrease the value by 1
      decrease() {
        let state = this.state;
        state.counter -= 1;
    //update state and trigger new rendering
        this.setState(state);
      }
    
      render() {
        return (
          <div>
            <h1>Counter</h1>
            <h3>
              <button onClick={this.decrease}>-</button>
              {this.state.counter}
              <button onClick={this.increase}>+</button>
            </h3>
          </div>
        );
      }
    }
    
    export default App;

    Explanation of the Code

    The App.js file defines a React component called App. Inside its constructor, we initialize a state object with a counter property set to 0.

    In React, components use two main types of data: props and state.

    • State Management: We use this.state to store and manage the counter value.
    • Binding Methods: The increase and decrease functions modify the counter state and are bound in the constructor.
    • Updating the UI: The render method returns a JSX structure containing a <h1> heading and a <h3> element with two buttons (+ and -) to update the counter value.
    • Handling Events: The buttons call this.increase and this.decrease on click, updating the state and re-rendering the component with the new counter value.

    The method render()defines the visual structure of the component:

    1. A “Counter” title
    2. A decrease (-) button that calls the method decrease when clicked
    3. The current value of the counter ( this.state.counter)
    4. A plus (+) button that calls the method increase when clicked

    Understanding Props and State in React

    • Props (Properties):
      • Props are immutable, meaning they cannot be modified within the component that receives them.
      • They are passed from parent components to child components.
      • Props allow for dynamic content to be rendered based on the parent component’s data.
    • State:
      • Unlike props, state is mutable, meaning it can be changed within the component.
      • The setState method is used to update the state and trigger a re-render of the component.
      • State is useful for interactive and dynamic elements, such as our counter.

    By understanding the difference between props and state, you can effectively manage data flow and component interactions in your React applications.

    Now you have a functional counter in React! Experiment with it, customize it, and explore more about React components and state management. Happy coding! ☕