Javascript and React overview and implementation examples

Machine Learning Artificial Intelligence Digital Transformation Programming Technology ICT Technology Javascript Web Technologies Navigation of this blog
Javascript

JavaScript is a programming language that is widely used in web development and application development. JavaScript makes it possible to add dynamic behavior and interactive elements to web pages and applications.

Below is an overview of the main features and usage of JavaScript.

Features:

  • Client-side processing: JavaScript is a client-side scripting language that runs primarily in the web browser, directly in the web page, and allows for user interaction and manipulation of the DOM (Document Object Model).
  • Dynamic Behavior: JavaScript can be used to add dynamic behavior to web pages and applications. This can be, for example, form validation, event handling, adding and removing elements, animation, etc.
  • Platform extensibility: JavaScript can be extended with plug-ins and libraries. There are many JavaScript libraries and frameworks (e.g., React.js, Angular.js, Vue.js) that can be used to build sophisticated web applications.

How to use:

  • Embedding scripts in HTML: JavaScript code can be embedded directly in HTML files using the <script> tag.
<script>
// Writing JavaScript code
</script>
  • Loading external files: JavaScript code can be created as an external file and loaded from an HTML file.
<script src="script.js"></script>

Main applications:

  • Event processing: Used to perform specific processing in response to user actions (clicks, keyboard input, etc.).
  • DOM manipulation: JavaScript can be used to search, add, delete, and modify elements of a web page.
  • Data retrieval and transmission: use Ajax or Fetch API to pass data to and from the server.
  • Animation: Create animation effects such as moving or fading elements.
    Form validation: Validate the data entered by the user to ensure its validity.

Specific usage (implementation) for each of these applications is described below.

Example of event processing implementation

A common way to implement event handling using JavaScript is as follows

Example of adding an event listener to an HTML element:

<button id="myButton">Click me!</button>
const button = document.getElementById('myButton');

button.addEventListener('click', function(event) {
  // Processing when a click event occurs
  console.log('Button clicked!');
});

In the above example, the getElementById() method is used to obtain an HTML element, and the addEventListener() method is used to add an event listener. Here, the specified process is executed when a click event occurs.

Use of event objects within event handler functions:

button.addEventListener('click', function(event) {
  // Obtain information about the element on which the click event occurred
  const targetElement = event.target;
  console.log('Button clicked!', targetElement);
});

In the above example, the event object is used within the event handler function. event.target can be used to obtain information about the element on which the event occurred.

Control of event propagation (event bubbling):

const parentElement = document.getElementById('parent');
const childElement = document.getElementById('child');

parentElement.addEventListener('click', function(event) {
  console.log('Parent clicked!');
});

childElement.addEventListener('click', function(event) {
  console.log('Child clicked!');
  event.stopPropagation(); // Stop propagation of events
});

In the above example, a click event listener is added to both the parent element and the child element, and event propagation (event bubbling) is stopped by calling event.stopPropagation() in the event handler of the childElement. In other words, the click event of the parent element is not executed when the click event of the child element occurs.

Example implementation of DOM manipulation using Javascript

The following is a general implementation example of DOM (Document Object Model) manipulation using JavaScript.

Example of retrieving an element and changing its attributes:

<div id="myElement">Hello, World!</div>
const element = document.getElementById('myElement');

// Change text
element.textContent = 'Hello, JavaScript!';

// Change Style
element.style.color = 'red';

// Adding Classes
element.classList.add('highlight');

// Change Attributes
element.setAttribute('data-value', '123');

In the above example, the getElementById() method is used to obtain an HTML element, and the properties and methods of that element are used to perform operations. Next, the textContent property is used to change the element’s text, the style property is used to change the style, the classList property is used to add or remove classes, and the setAttribute() method is used to change attributes.

Example of creating and adding an element:

const newElement = document.createElement('p');
newElement.textContent = 'This is a new paragraph.';

const container = document.getElementById('container');
container.appendChild(newElement);

In the above example, the createElement() method is used to create a new element, set the properties of that element, and use the appendChild() method to add the new element to the existing element.

An example of deleting an element:

const elementToRemove = document.getElementById('elementToRemove');
elementToRemove.remove();

In the above example, the remove() method is used to remove the specified element.

Example of adding an event listener:

const button = document.getElementById('myButton');
button.addEventListener('click', function(event) {
  console.log('Button clicked!');
});

In the above example, the addEventListener() method is used to add a listener for click events.

Example implementation of data acquisition and transmission using Javascript

The general method of retrieving and sending data using JavaScript is as follows.

Example implementation of data acquisition (GET request):

// Example of sending a GET request to retrieve data

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    // Process acquired data
    console.log(data);
  })
  .catch(error => {
    // error handling
    console.error('Failed to retrieve data.', error);
  });

In the above example, the fetch() method is used to send a GET request from a specified URL. fetch() works asynchronously, returning a Promise, and then() method is used to convert the response into JSON format and retrieve the data for further processing. The catch() method is used for error handling.

Example implementation of sending data (POST request):

// Example of sending a POST request to send data to the server

const dataToSend = { name: 'John', age: 25 };

fetch('https://api.example.com/submit', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(dataToSend)
})
  .then(response => response.json())
  .then(responseData => {
    // Process response
    console.log(responseData);
  })
  .catch(error => {
    // error handling
    console.error('Data transmission failed.', error);
  });

In the above example, a POST request is sent using the fetch() method, with options specified in the second argument of fetch(), ‘POST’ for the method, the format of the data to be sent specified in headers, and the data to be sent converted to JSON format and specified in body. The data to be sent is converted to JSON format and specified in the body.

In these examples, the JavaScript fetch() method is used to fetch and send data, but it is also common to use other libraries or frameworks (e.g., Axios, jQuery). In addition, since the process of fetching and sending data is done asynchronously, it is important to use Promise and async/await to ensure proper processing.

React

React is a JavaScript library and framework developed by Facebook that specializes in building user interfaces (UIs). React has a component-based architecture that allows for the creation of reusable UI elements.

Below is an overview of React’s main features and usage.

Features:

  • Component-based: React creates UI as reusable components. Each component is independent and can have its own state and properties (props).
  • Virtual DOM: React uses an in-memory representation called the virtual DOM to accelerate UI updates; React detects UI changes via the virtual DOM and updates the actual DOM with a minimum of DOM manipulation.
  • Unidirectional data flow: In React, data flow is controlled in one direction. Data is passed from parent components to child components, and when the state of a component changes, the UI is automatically re-rendered.

How to use:

  • Project setup: To set up a React project, install Node.js or npm (or Yarn) and use a tool such as Create React App.
  • Create components: React divides the UI into components. Each component is created as a JavaScript class or function.

An example is shown below.

import React from 'react';

class App extends React.Component {
render() {
return (
<div>
<h1>Hello, React!</h1>
</div>
              );
                  }
                                                                     }

export default App;

    JSX (JavaScript XML): React uses a proprietary syntax called JSX to describe the UI; JSX is similar to HTML and can be used in conjunction with JavaScript code.

    Main uses:

    • Building user interfaces: React is used to build UIs for web applications and mobile apps.
    • Single Page Application (SPA): React is well suited for SPA development; combined with React Router, it can be used to create SPAs with multiple pages.
      Mobile app development: React Native, a derivative of React, can be used to develop native mobile apps.

    Next, we will discuss an example implementation using React.

    Example of user interface implementation using React

    Below is an example of a user interface (UI) implementation using React. In this example, a simple task list UI is created.

    import React, { useState } from 'react';
    
    const TaskList = () => {
    const [tasks, setTasks] = useState([]);
    const [newTask, setNewTask] = useState('');
    
    const addTask = () => {
    if (newTask.trim() !== '') {
    setTasks([...tasks, newTask]);
    setNewTask('');
    }
    };
    
    const removeTask = (index) => {
    const updatedTasks = [...tasks];
    updatedTasks.splice(index, 1);
    setTasks(updatedTasks);
    };
    
    return (
    <div>
    <h1>Task List</h1>
    <input
    type="text"
    value={newTask}
    onChange={(e) => setNewTask(e.target.value)}
    />
    <button onClick={addTask}>Add Task</button>
    <ul>
    {tasks.map((task, index) => (
    <li key={index}>
    {task}
    <button onClick={() => removeTask(index)}>Remove</button>
    </li>
    ))}
    </ul>
    </div>
    );
    };
    
    export default TaskList;

    In the above example, we created a component called TaskList, in which we can add and remove tasks. The useState hook is used to manage the states tasks and newTask, where tasks holds an array of tasks and newTask holds the input values ​​for the new task. The addTask function takes care of adding a new task to tasks, adding a task only if the input value is not empty, and clearing the input value. The removeTask function removes the task with the specified index from tasks.

    In the return statement, the UI is written as JSX. Use <input> and <button> elements to create new task input and add buttons, and <ul> and <li> elements to display the list of tasks. Next to each task is a delete button, click to delete the corresponding task.

    SPA implementation example using React

    An implementation example of a simple SPA (single page application) using React is shown below.

    import React, { useState } from 'react';
    
    const Home = () => {
    return <h1>Welcome to the Home Page!</h1>;
    };
    
    const About = () => {
    return <h1>About Us</h1>;
    };
    
    const Contact = () => {
    const [message, setMessage] = useState('');
    
    const handleChange = (e) => {
    setMessage(e.target.value);
    };
    
    const handleSubmit = (e) => {
    e.preventDefault();
    alert(`Message: ${message}`);
    setMessage('');
    };
    
    return (
    <div>
    <h1>Contact Us</h1>
    <form onSubmit={handleSubmit}>
    <textarea value={message} onChange={handleChange} />
    <br />
    <button type="submit">Send Message</button>
    </form>
    </div>
    );
    };
    
    const App = () => {
    const [currentPage, setCurrentPage] = useState('home');
    
    const renderPage = () => {
    switch (currentPage) {
    case 'home':
    return <Home />;
    case 'about':
    return <About />;
    case 'contact':
    return <Contact />;
    default:
    return <Home />;
    }
    };
    
    const handleNavigation = (page) => {
    setCurrentPage(page);
    };
    
    return (
    <div>
    <nav>
    <button onClick={() => handleNavigation('home')}>Home</button>
    <button onClick={() => handleNavigation('about')}>About</button>
    <button onClick={() => handleNavigation('contact')}>Contact</button>
    </nav>
    <div>{renderPage()}</div>
    </div>
    );
    };
    
    export default App;

    In the example above, we created three components: Home, About, and Contact, and the App component manages the current page, page switching, and page component rendering. The renderPage function returns the correct page component according to the currentPage, and the handleNavigation function updates the currentPage according to the navigation button click event.

    The Contact component handles filling and submitting forms, uses the useState hook to manage message state, and uses the handleChange and handleSubmit functions to update state and submit messages. In the return statement, we display the navigation buttons and the current page component, and clicking the navigation button displays the corresponding page.

    In this example, we have created a simple SPA with three pages: Home, About, and Contact, and used React to implement user interactions such as page switching and form submission.

    Reference Information and Reference Books

    For more information on Javascript and React, see “Front-end Development with Javascript and React. For more information on Javascript and React, please refer to “Front-end Development with Javascript and React”. Also, please refer to “About Web Technology” and “Server Technology” for information on the web systems covered by Javascript.

    Reference book is “Learning JavaScript: JavaScript Essentials for Modern Application Development”

    Beginning JavaScript

    JavaScript: The Definitive Guide: Master the World’s Most-Used Programming Language”

    for React Reference book is “Learning React: Modern Patterns for Developing React Apps”

    React Cookbook”

    コメント

    タイトルとURLをコピーしました