Duong Tran

Duong Tran

1656762564

Tạo Và Sử Dụng Hook Tùy Chỉnh Của Riêng Mình Trong React js

Hướng dẫn rõ ràng này sẽ giúp bạn tìm hiểu cách tạo và sử dụng hook tùy chỉnh trong ứng dụng React bằng hook useState () mặc định.

Trong React, Hooks là các hàm đơn giản cho phép bạn khởi tạo trạng thái React, hơn nữa cho phép bạn tự do quản lý vòng đời của một thành phần.

Có hai mô hình chính, lớp và móc nếu bạn đã từng làm việc trên một thành phần lớp trong React. Sau đó, bạn phải biết hook không hoạt động với các lớp; nếu bạn viết mã trong các thành phần chức năng, thì chỉ có hook là dành cho bạn.

React cung cấp rất nhiều hook được xác định trước giúp quản lý hành vi của một thành phần chức năng. Nếu bạn đã làm việc với React trước đây, thì bạn phải lưu ý những điểm sau:

  • useEffect Hook
  • useRef Hook
  • useCallback Hook
  • useMemo Hook
  • useContext Hook
  • useReducer Hook

Nhưng bạn có biết bạn cũng có thể tạo hook tùy chỉnh của riêng mình trong ứng dụng React không? Vâng, đó là sự thật, đôi khi bạn có thể rơi vào một tình huống đặc biệt, nơi bạn phải quản lý hành vi của một thành phần.

Trong trường hợp đó, bạn có thể xây dựng một hook tùy chỉnh và xử lý hành vi của nó dựa trên các yêu cầu ứng dụng React của bạn.

Hãy cùng chúng tôi tìm hiểu cách thực hiện?

Hướng dẫn xây dựng và sử dụng React Js Custom Hook

  • Bước 1: Thiết lập dự án React
  • Bước 2: Thêm gói Bootstrap
  • Bước 3: Tạo tệp Hook
  • Bước 4: Sử dụng móc tùy chỉnh
  • Bước 5: Chạy React Server

Thiết lập dự án React

Để thiết lập ứng dụng React mới, bạn phải thiết lập Node và npm trên hệ thống phát triển của mình.

Nếu nút và npm được cài đặt, hãy mở trình chỉnh sửa mã của bạn và chuyển đến ứng dụng đầu cuối của bạn.

Bắt đầu viết lệnh được cung cấp và chạy lệnh sau đó.

npx create-react-app react-blog

Sau khi công cụ tạo-phản ứng-ứng dụng tải xuống dự án mới.

Đảm bảo rằng bạn đã có bên trong thư mục dự án.

cd react-blog

Thêm gói Bootstrap

Nếu bạn muốn phát triển các thành phần UI với tốc độ cao theo cấp số nhân. Thư viện Bootstrap là lựa chọn tốt nhất. Tuy nhiên, nó không chỉ là giải pháp duy nhất.

Trong phần lệnh bên dưới, bạn thấy một lệnh bạn phải chạy lệnh đó để cài đặt gói.

npm install bootstrap

Cài đặt bootstrap là chưa đủ, nó phải được đăng ký trong tệp App.js.

Sau đó, bạn sẽ không phải viết CSS tùy chỉnh để tạo các thành phần giao diện người dùng.

import 'bootstrap/dist/css/bootstrap.min.css'

Bây giờ, Bootstrap đã hoàn chỉnh và đang chạy và sẵn sàng chinh phục phần giao diện người dùng của ứng dụng nhỏ của chúng tôi.

Tạo tệp Hook

Trong thư mục dự án của bạn, hãy tạo một tên thư mục khác mà nó kết nối . Trong thư mục này, chúng ta sẽ tạo và giữ tệp hook tùy chỉnh.

Tiếp theo, tạo tệp useCounter.js ; bạn phải nhập hook useState trong tệp này.

Cuối cùng, hãy tạo một hàm tùy chỉnh và viết mã đã cho để tạo thành móc tùy chỉnh của riêng bạn.

import { useState } from 'react'
export default function useCounter() {
  const [addCount, initCounter] = useState({ counter: 0 })
  const onCounterClick = () => {
    initCounter({ counter: addCount.counter + 1 })
  }
  return { addCount, onCounterClick }
}

Sử dụng móc tùy chỉnh

Chúng tôi đã tạo thành công hook trong react và bây giờ bạn sẽ tìm hiểu cách sử dụng hook tùy chỉnh trong thành phần js của ứng dụng chính.

Mở tệp app.js và thêm mã vào tệp.

import React from 'react'
import useCounter from './hooks/useCounter.js'
import 'bootstrap/dist/css/bootstrap.min.css'
export default function App() {
  const hookCustom = useCounter()
  return (
    <div className="container mt-5">
      <h2>Build Custom Hook in React</h2>
      <div className="mt-2 mb-3">
        Add counter: <strong>{hookCustom.addCount.counter}</strong>
      </div>
      <div className="d-grid">
        <button
          type="button"
          className="btn btn-dark"
          onClick={hookCustom.onCounterClick}
        >
          Add Counter
        </button>
      </div>
    </div>
  )
}

Chạy máy chủ React

Bộ đếm đã sẵn sàng, bạn chỉ có thể kiểm tra sau khi chạy máy chủ phát triển React.

Để khởi động máy chủ ứng dụng phản ứng, bạn cần chạy lệnh sau từ dấu nhắc lệnh.

npm start

React Js Tạo và Sử dụng Hướng dẫn Hook Tùy chỉnh Riêng

Sự kết luận

Trong hướng dẫn móc tùy chỉnh React này, chúng tôi đã cung cấp cho bạn bản demo về cách xây dựng móc tùy chỉnh của riêng bạn trong React. Chúng tôi đã tạo một móc đồng hồ bộ đếm, trong đó số bộ đếm tăng lên sau mỗi lần nhấp.

Ngoài ra, chúng ta cũng đã học cách sử dụng một hook tùy chỉnh trong thành phần React thông qua ví dụ mã thực tế này.

Chúng tôi đã cố gắng hết sức để chia sẻ và thuyết phục về tất cả các quy trình, hy vọng bạn thích hướng dẫn này.

Nguồn: https://www.positronx.io/react-js-create-and-use-own-custom-hook-tutorial/

#reactjs 

Tạo Và Sử Dụng Hook Tùy Chỉnh Của Riêng Mình Trong React js
顾 静

顾 静

1656758724

在 React Js 中创建和使用自己的自定义 Hook

这个权威指南将帮助你学习如何使用默认的 useState() 钩子在 React 应用程序中创建和使用自定义钩子。

在 React 中,Hooks 是简单的函数,允许您启动 React 状态,此外还让您可以自由管理组件的生命周期。

如果您曾经在 React 中处理过类组件,那么有两个主要的范例、类和钩子。那么你必须知道钩子不适用于类;如果您在功能组件中编写代码,那么只有钩子适合您。

React 提供了大量预定义的钩子来帮助管理功能组件的行为。如果您以前使用过 React,那么您必须了解以下钩子:

  • 使用效果挂钩
  • 使用参考挂钩
  • 使用回调挂钩
  • 使用Memo Hook
  • 使用上下文挂钩
  • 使用Reducer Hook

但是你知道你也可以在 React 应用程序中创建自己的自定义钩子吗?嗯,确实如此,有时您可能会遇到一种特殊情况,您必须管理组件的行为。

在这种情况下,您可以构建一个自定义钩子并根据您的 React 应用程序要求处理其行为。

让我们看看怎么做?

React Js 构建和使用自定义 Hook 教程

  • 第 1 步:设置 React 项目
  • 第 2 步:添加引导程序包
  • 第 3 步:创建挂钩文件
  • 第 4 步:使用自定义挂钩
  • 第 5 步:运行 React 服务器

设置 React 项目

为了设置新的 React 应用程序,您必须在开发系统上设置 Node 和 npm。

如果安装了 node 和 npm,请打开您的代码编辑器,然后转到您的终端应用程序。

开始编写提供的命令,然后运行该命令。

npx create-react-app react-blog

在 create-react-app 工具下载新项目后。

确保您已进入项目目录。

cd react-blog

添加引导程序包

如果您想以指数级高速开发 UI 组件。Bootstrap 库是最好的选择。然而,它不仅仅是唯一的解决方案。

在下面的命令部分中,您会看到一个命令,您必须运行该命令才能安装软件包。

npm install bootstrap

安装 bootstrap 是不够的,它必须在App.js文件中注册。

在此之后,您将不必编写自定义 CSS 来创建用户界面组件。

import 'bootstrap/dist/css/bootstrap.min.css'

现在,Bootstrap 已完全启动并运行,并准备好征服我们小应用程序的 UI 部分。

创建挂钩文件

在您的项目目录中,创建另一个目录名称它hooks。在此文件夹中,我们将创建并保留自定义挂钩文件。

接下来,创建useCounter.js文件;您必须在此文件中导入 useState 挂钩。

最终,创建一个自定义函数并编写给定的代码以形成您自己的自定义钩子。

import { useState } from 'react'
export default function useCounter() {
  const [addCount, initCounter] = useState({ counter: 0 })
  const onCounterClick = () => {
    initCounter({ counter: addCount.counter + 1 })
  }
  return { addCount, onCounterClick }
}

使用自定义挂钩

我们已经成功地在 react 中创建了 hook,现在您将了解如何在主 app js 组件中使用自定义 hook。

打开app.js文件并将代码添加到文件中。

import React from 'react'
import useCounter from './hooks/useCounter.js'
import 'bootstrap/dist/css/bootstrap.min.css'
export default function App() {
  const hookCustom = useCounter()
  return (
    <div className="container mt-5">
      <h2>Build Custom Hook in React</h2>
      <div className="mt-2 mb-3">
        Add counter: <strong>{hookCustom.addCount.counter}</strong>
      </div>
      <div className="d-grid">
        <button
          type="button"
          className="btn btn-dark"
          onClick={hookCustom.onCounterClick}
        >
          Add Counter
        </button>
      </div>
    </div>
  )
}

运行反应服务器

计数器已准备就绪,只有在运行 React 开发服务器后才能进行测试。

要启动 react 应用服务器,您需要从命令提示符运行以下命令。

npm start

React Js 创建和使用自己的自定义 Hook 教程

结论

在这个 React 自定义钩子教程中,我们为您提供了一个在 React 中构建自己的自定义钩子的演示。我们创建了一个计数器时钟挂钩,每次点击都会增加一个计数器编号。

除此之外,我们还通过这个实际的代码示例学习了如何在 React 组件中使用自定义钩子。

我们尽最大努力分享和说服所有流程,希望您喜欢本指南。

来源:https ://www.positronx.io/react-js-create-and-use-own-custom-hook-tutorial/

#reactjs 

在 React Js 中创建和使用自己的自定义 Hook

Cree Y Use Su Propio Gancho Personalizado En React js

Esta guía definitiva lo ayudará a aprender cómo crear y usar un gancho personalizado en la aplicación React usando el gancho predeterminado useState().

En React, los Hooks son funciones simples que le permiten iniciar el estado de React, además le da la libertad de administrar el ciclo de vida de un componente.

Hay dos paradigmas principales, clases y ganchos si alguna vez ha trabajado en un componente de clase en React. Entonces debes saber que los ganchos no funcionan con clases; si escribe código en componentes funcionales, entonces solo los ganchos son para usted.

React ofrece toneladas de ganchos predefinidos que ayudan a administrar el comportamiento de un componente funcional. Si ha trabajado con React antes, debe tener en cuenta los siguientes ganchos:

  • useEffect Hook
  • UseRef Gancho
  • useCallback Hook
  • useMemo Hook
  • Gancho useContext
  • utilizar gancho reductor

Pero, ¿sabe que también puede crear su propio enlace personalizado en la aplicación React? Bueno, eso es cierto, a veces puede encontrarse en una situación peculiar en la que debe administrar el comportamiento de un componente.

En ese caso, puede crear un enlace personalizado y manejar su comportamiento en función de los requisitos de su aplicación React.

¿Vamos a averiguar cómo hacerlo?

Tutorial de compilación y uso de ganchos personalizados de React Js

  • Paso 1: configurar el proyecto React
  • Paso 2: agregue el paquete Bootstrap
  • Paso 3: Crear archivo de enlace
  • Paso 4: use un gancho personalizado
  • Paso 5: Ejecute el servidor React

Configurar proyecto React

Para configurar la nueva aplicación React, debe configurar Node y npm en su sistema de desarrollo.

Si node y npm están instalados, abra su editor de código y vaya a su aplicación de terminal.

Comience a escribir el comando proporcionado y ejecútelo después.

npx create-react-app react-blog

Después de que la herramienta create-react-app descargó el nuevo proyecto.

Asegúrese de haber ingresado al directorio del proyecto.

cd react-blog

Agregar paquete de Bootstrap

Si desea desarrollar componentes de interfaz de usuario a una velocidad exponencialmente alta. La biblioteca Bootstrap es la mejor opción. Sin embargo, no es sólo la única solución.

En la siguiente sección de comandos, verá un comando que debe ejecutar para instalar el paquete.

npm install bootstrap

Instalar bootstrap no es suficiente, debe registrarse en el archivo App.js.

Después de esto, no tendrá que escribir CSS personalizado para crear los componentes de la interfaz de usuario.

import 'bootstrap/dist/css/bootstrap.min.css'

Ahora, Bootstrap está completamente funcionando y listo para conquistar la parte de la interfaz de usuario de nuestra pequeña aplicación.

Crear archivo de enlace

En el directorio de su proyecto, cree otro nombre de directorio que enganche . En esta carpeta, vamos a crear y mantener el archivo de enlace personalizado.

A continuación, cree el archivo useCounter.js ; tiene que importar el enlace useState en este archivo.

Eventualmente, cree una función personalizada y escriba el código dado para formar su propio gancho personalizado.

import { useState } from 'react'
export default function useCounter() {
  const [addCount, initCounter] = useState({ counter: 0 })
  const onCounterClick = () => {
    initCounter({ counter: addCount.counter + 1 })
  }
  return { addCount, onCounterClick }
}

Usar gancho personalizado

Hemos creado con éxito el gancho en reaccionar, y ahora descubrirá cómo usar el gancho personalizado en el componente js de la aplicación principal.

Abra el archivo app.js y agregue el código en el archivo.

import React from 'react'
import useCounter from './hooks/useCounter.js'
import 'bootstrap/dist/css/bootstrap.min.css'
export default function App() {
  const hookCustom = useCounter()
  return (
    <div className="container mt-5">
      <h2>Build Custom Hook in React</h2>
      <div className="mt-2 mb-3">
        Add counter: <strong>{hookCustom.addCount.counter}</strong>
      </div>
      <div className="d-grid">
        <button
          type="button"
          className="btn btn-dark"
          onClick={hookCustom.onCounterClick}
        >
          Add Counter
        </button>
      </div>
    </div>
  )
}

Ejecutar servidor React

El contador está listo, solo puede probarlo después de ejecutar el servidor de desarrollo de React.

Para iniciar el servidor de aplicaciones de reacción, debe ejecutar el siguiente comando desde el símbolo del sistema.

npm start

Tutorial de React Js Crear y usar su propio gancho personalizado

Conclusión

En este tutorial de gancho personalizado de React, le dimos una demostración de cómo crear su propio gancho personalizado en React. Creamos un gancho de reloj contador, donde un número de contador aumenta con cada clic.

Aparte de eso, también aprendimos cómo usar un enlace personalizado en el componente React a través de este ejemplo de código práctico.

Hicimos todo lo posible para compartir y persuadir sobre todos los procesos, espero que les guste esta guía.

Fuente: https://www.positronx.io/react-js-create-and-use-own-custom-hook-tutorial/

#reactjs 

Cree Y Use Su Propio Gancho Personalizado En React js
Rui  Silva

Rui Silva

1656752400

Crie E Use O Próprio Gancho Personalizado No React js

Este guia definitivo irá ajudá-lo a aprender como criar e usar um hook customizado no aplicativo React usando o hook useState() padrão.

No React, Hooks são funções simples que permitem iniciar o estado React, além de lhe dar a liberdade de gerenciar o ciclo de vida de um componente.

Existem dois paradigmas principais, classes e ganchos se você já trabalhou em um componente de classe no React. Então você deve saber que hooks não funcionam com classes; se você escrever código em componentes funcionais, apenas os ganchos são para você.

O React oferece vários ganchos predefinidos que ajudam a gerenciar o comportamento de um componente funcional. Se você já trabalhou com React antes, deve estar ciente dos seguintes ganchos:

  • use Gancho de Efeitos
  • use o Gancho de Referência
  • use o Gancho de Retorno
  • useMemo Hook
  • use o Gancho de Contexto
  • useReducer Hook

Mas você sabe que também pode criar seu próprio hook customizado no aplicativo React? Bem, isso é verdade, às vezes você pode entrar em uma situação peculiar em que precisa gerenciar o comportamento de um componente.

Nesse caso, você pode criar um gancho personalizado e lidar com seu comportamento com base nos requisitos do aplicativo React.

Vamos descobrir como fazer?

React Js Build and Use Custom Hook Tutorial

  • Etapa 1: configurar o projeto React
  • Etapa 2: adicionar o pacote Bootstrap
  • Etapa 3: criar arquivo de gancho
  • Etapa 4: use o gancho personalizado
  • Etapa 5: execute o servidor React

Configurar projeto React

Para configurar o novo aplicativo React, você deve configurar o Node e o npm em seu sistema de desenvolvimento.

Se node e npm estiverem instalados, abra seu editor de código e acesse seu aplicativo de terminal.

Comece a escrever o comando fornecido e execute o comando depois.

npx create-react-app react-blog

Após a ferramenta create-react-app baixar o novo projeto.

Certifique-se de ter entrado no diretório do projeto.

cd react-blog

Adicionar pacote Bootstrap

Se você deseja desenvolver componentes de interface do usuário em velocidade exponencialmente alta. A biblioteca Bootstrap é a melhor opção. No entanto, não é apenas a única solução.

Na seção de comando abaixo, você vê um comando para executar esse comando para instalar o pacote.

npm install bootstrap

Não basta instalar o bootstrap, ele deve ser registrado no arquivo App.js.

Depois disso, você não precisará escrever CSS personalizado para criar os componentes da interface do usuário.

import 'bootstrap/dist/css/bootstrap.min.css'

Agora, o Bootstrap está totalmente em funcionamento e pronto para conquistar a parte da interface do usuário do nosso pequeno aplicativo.

Criar arquivo de gancho

No diretório do seu projeto, crie outro nome de diretório que ele conecta . Nesta pasta, vamos criar e manter o arquivo de gancho personalizado.

Em seguida, crie o arquivo useCounter.js ; você tem que importar o gancho useState neste arquivo.

Eventualmente, crie uma função personalizada e escreva o código fornecido para formar seu próprio gancho personalizado.

import { useState } from 'react'
export default function useCounter() {
  const [addCount, initCounter] = useState({ counter: 0 })
  const onCounterClick = () => {
    initCounter({ counter: addCount.counter + 1 })
  }
  return { addCount, onCounterClick }
}

Usar gancho personalizado

Criamos com sucesso o hook em react, e agora você descobrirá como usar o custom hook no componente principal do app js.

Abra o arquivo app.js e adicione o código ao arquivo.

import React from 'react'
import useCounter from './hooks/useCounter.js'
import 'bootstrap/dist/css/bootstrap.min.css'
export default function App() {
  const hookCustom = useCounter()
  return (
    <div className="container mt-5">
      <h2>Build Custom Hook in React</h2>
      <div className="mt-2 mb-3">
        Add counter: <strong>{hookCustom.addCount.counter}</strong>
      </div>
      <div className="d-grid">
        <button
          type="button"
          className="btn btn-dark"
          onClick={hookCustom.onCounterClick}
        >
          Add Counter
        </button>
      </div>
    </div>
  )
}

Executar servidor React

O contador está pronto, você pode testar somente após executar o servidor de desenvolvimento React.

Para iniciar o servidor de aplicativos reagir, você precisa executar o seguinte comando no prompt de comando.

npm start

React Js Criar e usar o próprio tutorial de gancho personalizado

Conclusão

Neste tutorial de gancho personalizado do React, demos a você uma demonstração de como construir seu próprio gancho personalizado no React. Criamos um gancho de contador, onde um número de contador aumenta a cada clique.

Além disso, também aprendemos como usar um hook customizado no componente React através deste exemplo de código prático.

Nós tentamos o nosso melhor para compartilhar e persuadir sobre todos os processos, espero que você ame este guia.

Fonte: https://www.positronx.io/react-js-create-and-use-own-custom-hook-tutorial/

#reactjs 

Crie E Use O Próprio Gancho Personalizado No React js

ReactJsで独自のカスタムフックを作成して使用する

この決定的なガイドは、デフォルトのuseState()フックを使用してReactアプリケーションでカスタムフックを作成および使用する方法を学ぶのに役立ちます。

Reactでは、フックはReact状態を開始できる単純な関数であり、さらにコンポーネントのライフサイクルを自由に管理できます。

Reactでクラスコンポーネントに取り組んだことがある場合は、2つの主要なパラダイム、クラス、およびフックがあります。次に、フックがクラスで機能しないことを知っておく必要があります。機能コンポーネントでコードを書く場合は、フックだけが適しています。

Reactは、機能コンポーネントの動作を管理するのに役立つ多数の事前定義されたフックを提供します。以前にReactを使用したことがある場合は、次のフックに注意する必要があります。

  • useEffectフック
  • useRefフック
  • useCallbackフック
  • useMemoフック
  • useContextフック
  • useReducerフック

しかし、Reactアプリケーションで独自のカスタムフックを作成することもできることをご存知ですか?そうですね、コンポーネントの動作を管理しなければならないという特殊な状況に陥ることがあります。

その場合、カスタムフックを作成し、Reactアプリの要件に基づいてその動作を処理できます。

それを行う方法を見つけましょう?

ReactJsビルドとカスタムフックチュートリアルの使用

  • ステップ1: Reactプロジェクトを設定する
  • ステップ2:ブートストラップパッケージを追加する
  • ステップ3:フックファイルを作成する
  • ステップ4:カスタムフックを使用する
  • ステップ5: Reactサーバーを実行する

Reactプロジェクトを設定する

新しいReactアプリをセットアップするには、開発システムでNodeとnpmをセットアップする必要があります。

nodeとnpmがインストールされている場合は、コードエディターを開き、ターミナルアプリに移動します。

提供されたコマンドの記述を開始し、その後コマンドを実行します。

npx create-react-app react-blog

create-react-appツールが新しいプロジェクトをダウンロードした後。

プロジェクトディレクトリ内にいることを確認してください。

cd react-blog

ブートストラップパッケージを追加する

指数関数的に高速でUIコンポーネントを開発したい場合。Bootstrapライブラリが最適なオプションです。ただし、それが唯一の解決策ではありません。

以下のコマンドセクションには、パッケージをインストールするためにそのコマンドを実行する必要があるコマンドが表示されます。

npm install bootstrap

ブートストラップをインストールするだけでは不十分です。App.jsファイルに登録する必要があります。

この後、ユーザーインターフェイスコンポーネントを作成するためにカスタムCSSを作成する必要はありません。

import 'bootstrap/dist/css/bootstrap.min.css'

これで、Bootstrapが完全に稼働し、小さなアプリのUI部分を征服する準備が整いました。

フックファイルを作成する

プロジェクトディレクトリに、フックする別のディレクトリ名を作成します。このフォルダに、カスタムフックファイルを作成して保持します。

次に、useCounter.jsファイルを作成します。このファイルにuseStateフックをインポートする必要があります。

最終的に、カスタム関数を作成し、指定されたコードを記述して独自のカスタムフックを形成します。

import { useState } from 'react'
export default function useCounter() {
  const [addCount, initCounter] = useState({ counter: 0 })
  const onCounterClick = () => {
    initCounter({ counter: addCount.counter + 1 })
  }
  return { addCount, onCounterClick }
}

カスタムフックを使用する

これで、reactでフックが正常に作成されました。次に、メインのアプリjsコンポーネントでカスタムフックを使用する方法を説明します。

app.jsファイルを開き、ファイルにコードを追加します。

import React from 'react'
import useCounter from './hooks/useCounter.js'
import 'bootstrap/dist/css/bootstrap.min.css'
export default function App() {
  const hookCustom = useCounter()
  return (
    <div className="container mt-5">
      <h2>Build Custom Hook in React</h2>
      <div className="mt-2 mb-3">
        Add counter: <strong>{hookCustom.addCount.counter}</strong>
      </div>
      <div className="d-grid">
        <button
          type="button"
          className="btn btn-dark"
          onClick={hookCustom.onCounterClick}
        >
          Add Counter
        </button>
      </div>
    </div>
  )
}

Reactサーバーを実行する

カウンターの準備ができました。React開発サーバーを実行した後にのみテストできます。

反応アプリサーバーを起動するには、コマンドプロンプトから次のコマンドを実行する必要があります。

npm start

ReactJs独自のカスタムフックチュートリアルを作成して使用

結論

このReactカスタムフックチュートリアルでは、Reactで独自のカスタムフックを構築するデモを提供しました。クリックするたびにカウンター数が増えるカウンタークロックフックを作成しました。

それとは別に、この実用的なコード例を通じて、Reactコンポーネントでカスタムフックを使用する方法も学びました。

私たちはすべてのプロセスに関して共有し、説得するために最善を尽くしました。あなたがこのガイドを気に入ってくれることを願っています。

ソース:https ://www.positronx.io/react-js-create-and-use-own-custom-hook-tutorial/

#reactjs 

ReactJsで独自のカスタムフックを作成して使用する

Create and Use Own Custom Hook in React Js

This definitive guide will help you learn how to create and use custom hook in React application using the default useState() hook.

In React, Hooks are simple functions that allow you to initiate React state, furthermore gives you the freedom to manage the lifecycle of a component.

There are two primary paradigms, classes, and hooks if you have ever worked on a class component in React. Then you must know hooks don’t work with classes; if you write code in functional components, then only hooks are for you.

See more at : https://www.positronx.io/react-js-create-and-use-own-custom-hook-tutorial/

#reactjs 

Create and Use Own Custom Hook in React Js
Vinnie  Erdman

Vinnie Erdman

1656484560

Final Changes (Error & States) for Movie Website in React JS

Welcome, to the Movie Website using React JS. Today, in this video we will tackle a few bug or error that is present on our website.

♥ Free Source Code Link: https://www.thapatechnical.com/2022/06/movie-website-in-react-js.html

------ TimeLine -----------
0:00 Intro
0:45 Free Source Code
1:10 What we are going to do?
1:50 Error Handling
4:40 Debounce
5:20 Loading State
7:30 One Final Bug Solve
8:45 Outro

#react #reactjs

Final Changes (Error & States) for Movie Website in React JS
Vinnie  Erdman

Vinnie Erdman

1656477240

How to Implement Debounce Functionality for Movie Website in React JS

Welcome, We will see how to implement Debounce Functionality in React JS in Hindi?

♥ Free Source Code Link: https://www.thapatechnical.com/2022/06/movie-website-in-react-js.html

------ TimeLine -----------
0:00 Intro
0:28 What is Debounce?
3:00 Debounce Code
7:55 Final Change
8:25 Outro

#react #reactjs

How to Implement Debounce Functionality for Movie Website in React JS
Zachary Palmer

Zachary Palmer

1656473587

How to Folder Structure from Small to Large React Projects

React Folder Structure Best Practices - For Large Projects

This is the folder structure pattern I follow whenever working on a big React application.


React Folder Structure in 5 Steps

 

How to structure large React applications into folders and files is a highly opinionated topic. I struggled for a while writing about this topic, because there is no right way to do it. However, every other week people ask me about how I structure my React projects -- with folder structures from small to large React projects.

After implementing React applications for a few years now, I want to give you a breakdown on how I approach this matter for my personal projects, for my freelance projects, and for my React workshops. It only takes 5 steps, and you decide what makes sense to you and how far you want to push it. So let's get started.

For anyone who says "I move files around until it feels right": This may be alright as a solo developer, but is that really something you would do in a cross-functional team of 4 developers with a total of 5 cross-functional teams in a company? At a higher scale of teams, it becomes tricky to "just move files around without a clear vision". In addition, this is nothing I could tell my consulting clients when they ask me about this matter. Hence, thake this walkthrough as reference guide for anyone who is looking for clarity about this subject.

SINGLE REACT FILE

The first step follows the rule: One file to rule them all. Most React projects start with a src/ folder and one src/App.js file with an App component. At least that's what you get when you are using create-react-app. It's a function component which just renders JSX:

import * as React from 'react';

const App = () => {
  const title = 'React';

  return (
    <div>
      <h1>Hello {title}</h1>
    </div>
  );
}

export default App;

Eventually this component adds more features, it naturally grows in size, and needs to extract parts of it as standalone React components. Here we are extracting a React list component with another child component from the App component:

import * as React from 'react';

const list = [
  {
    id: 'a',
    firstname: 'Robin',
    lastname: 'Wieruch',
    year: 1988,
  },
  {
    id: 'b',
    firstname: 'Dave',
    lastname: 'Davidds',
    year: 1990,
  },
];

const App = () => <List list={list} />;

const List = ({ list }) => (
  <ul>
    {list.map(item => (
      <ListItem key={item.id} item={item} />
    ))}
  </ul>
);

const ListItem = ({ item }) => (
  <li>
    <div>{item.id}</div>
    <div>{item.firstname}</div>
    <div>{item.lastname}</div>
    <div>{item.year}</div>
  </li>
);

Whenever you start with a new React project, I tell people it's fine to have multiple components in one file. It's even tolerable in a larger React application, whenever one component is strictly tight to another one. However, in this scenario, eventually this one file will not be sufficient anymore for your React project. That's when we transition to step two.

MULTIPLE REACT FILES

The second step follows the rule: Multiple files to rule them all. Take for instance our previous App component with its List and ListItem components: Rather than having everything in one src/App.js file, we can split these components up into multiple files. You decide how far you want to take it here. For example, I would go with the following folder structure:

- src/
--- App.js
--- List.js

While the src/List.js file would have the implementation details of the List and ListItem components, it would only export the List component from the file as public API of this file:

const List = ({ list }) => (
  <ul>
    {list.map(item => (
      <ListItem key={item.id} item={item} />
    ))}
  </ul>
);

const ListItem = ({ item }) => (
  <li>
    <div>{item.id}</div>
    <div>{item.firstname}</div>
    <div>{item.lastname}</div>
    <div>{item.year}</div>
  </li>
);

export { List };

Next the src/App.js file can import the List component and use it:

import * as React from 'react';

import { List } from './List';

const list = [ ... ];

const App = () => <List list={list} />;

If you would take this one step further, you could also extract the ListItem component into its own file and let the List component import the ListItem component:

- src/
--- App.js
--- List.js
--- ListItem.js

However, as said before, this may take it too far, because at this point in time the ListItem component is tightly coupled to the List component and therefore it would be okay to leave it in the src/List.js file. I follow the rule of thumb that whenever a React component becomes a reusable React component, I split it out as a standalone file, like we did with the List component, to make it accessible for other React components.

FROM REACT FILES TO REACT FOLDERS

 

From here, it becomes more interesting yet also more opinionated. Every React component grows in complexity eventually. Not only because more logic is added (e.g. more JSX with conditional rendering or logic with React Hooks and event handlers), but also because there are more technical concerns like styles and tests. A naive approach would be to add more files next to each React component. For example, let's say every React component has a test and a style file:

- src/
--- App.js
--- App.test.js
--- App.css
--- List.js
--- List.test.js
--- List.css

One can already see that this doesn't scale well, because with every additional component in the src/ folder we will lose more sight of every individual component. That's why I like to have one folder for each React component:

- src/
--- App/
----- index.js
----- component.js
----- test.js
----- style.css
--- List/
----- index.js
----- component.js
----- test.js
----- style.css

While the new style and test files implement styling and testing for each local component respectively, the new component.js file holds the actual implementation logic of the component. What's missing is the new index.js file which represents the public interface of the folder where everything gets exported that's relevant to the outside world. For example, for the List component it most often looks like this:

export * from './List';

The App component in its component.js file can still import the List component the following way:

import { List } from '../List/index.js';

In JavaScript, we can omit the /index.js for the imports, because it's the default:

import { List } from '../List';

The naming of these files is already opinionated: For example, test.js can become spec.js or style.css can become styles.css if a pluralization of files is desired. Moreover, if you are not using CSS but something like Styled Components, your file extension may change from style.css to style.js too.

Once you get used to this naming convention of folders and files, you can just search for "List component" or "App test" in your IDE for opening each file. Here I admit, in contrast to my personal taste of concise file names, that people often prefer to be more verbose with their file names:

- src/
--- App/
----- index.js
----- App.js
----- App.test.js
----- App.style.css
--- List/
----- index.js
----- List.js
----- List.test.js
----- List.style.css

Anway, if you collapse all component folders, regardless of the file names, you have a very concise and clear folder structure:

- src/
--- App/
--- List/

If there are more technical concerns for a component, for example you may want to extract custom hooks, types (e.g. TypeScript defined types), stories (e.g. Storybook), utilities (e.g. helper functions), or constants (e.g. JavaScript constants) into dedicated files, you can scale this approach horizontally within the component folder:

- src/
--- App/
----- index.js
----- component.js
----- test.js
----- style.css
----- types.js
--- List/
----- index.js
----- component.js
----- test.js
----- style.css
----- hooks.js
----- story.js
----- types.js
----- utils.js
----- constants.js

If you decide to keep your List/component.js more lightweight by extracting the ListItem component in its own file, then you may want to try the following folder structure:

- src/
--- App/
----- index.js
----- component.js
----- test.js
----- style.css
--- List/
----- index.js
----- component.js
----- test.js
----- style.css
----- ListItem.js

Here again, you can go one step further by giving the component its own nested folder with all other technical concerns like tests and styles:

- src/
--- App/
----- index.js
----- component.js
----- test.js
----- style.css
--- List/
----- index.js
----- component.js
----- test.js
----- style.css
----- ListItem/
------- index.js
------- component.js
------- test.js
------- style.css

Important: From here on you need to be careful not to nest too deeply your components into each other. My rule of thumb is that I am never nesting components more than two levels, so the List and ListItem folders as they are right now would be alright, but the ListItem's folder shouldn't have another nested folder. Exceptions prove the rule though.

After all, if you are not going beyond midsize React projects, this is in my opinion the way to go to structure your React components. In my experience as a React freelancer many React projects follow this organization of a React application.

TECHNICAL FOLDERS

 

The next step will help you to structure midsize to large React applications. It separates React components from reusable React utilities such as hooks and context, but also none React related utilities like helper functions (here services/). Take the following baseline of a folder structure as example:

- src/
--- components/
----- App/
------- index.js
------- component.js
------- test.js
------- style.css
----- List/
------- index.js
------- component.js
------- test.js
------- style.css

All previous React components got grouped into a new components/ folder. This gives us another vertical layer for creating folders for other technical categories. For example, at some point you may have reusable React Hooks that can be used by more than one component. So instead of coupling a custom hook tightly to a component, you can put the implementation of it in a dedicated folder which can be used by all React components:

- src/
--- components/
----- App/
------- index.js
------- component.js
------- test.js
------- style.css
----- List/
------- index.js
------- component.js
------- test.js
------- style.css
--- hooks/
----- useClickOutside.js
----- useScrollDetect.js

This doesn't mean that all hooks should end up in this folder though. React Hooks which are still only used by one component should remain in the component's file or a hooks.js file next to the component in the component's folder. Only reusable hooks end up in the new hooks/ folder. If there are more files needed for one hook, you can change it into a folder again:

- src/
--- components/
----- App/
------- index.js
------- component.js
------- test.js
------- style.css
----- List/
------- index.js
------- component.js
------- test.js
------- style.css
--- hooks/
----- useClickOutside/
------- index.js
------- hook.js
------- test.js
----- useScrollDetect/
------- index.js
------- hook.js
------- test.js

The same strategy may apply if you are using React Context in your React project. Because context needs to get instantiated somewhere, a dedicated folder/file for it is a best practice, because it needs to be accessible by many React components eventually:

- src/
--- components/
----- App/
------- index.js
------- component.js
------- test.js
------- style.css
----- List/
------- index.js
------- component.js
------- test.js
------- style.css
--- hooks/
----- useClickOutside.js
----- useScrollDetect.js
--- context/
----- Session.js

From here, there may be other utilities which need to be accessible from your components/ folder, but also from the other new folders such as hooks/ and context/. For miscellaneous utilities, I usually create a services/ folder. The name is up to you (e.g. utils/ is another folder name I see quite often, but services makes more sense for the following import strategy). But again, it's the principal of making logic available to other code in our project which drives this technical separation:

- src/
--- components/
----- App/
------- index.js
------- component.js
------- test.js
------- style.css
----- List/
------- index.js
------- component.js
------- test.js
------- style.css
--- hooks/
----- useClickOutside.js
----- useScrollDetect.js
--- context/
----- Session.js
--- services/
----- ErrorTracking/
------- index.js
------- service.js
------- test.js
----- Format/
------- Date/
--------- index.js
--------- service.js
--------- test.js
------- Currency/
--------- index.js
--------- service.js
--------- test.js

Take for instance the Date/index.js file. The implementation details may look like the following:

export const formatDateTime = (date) =>
  new Intl.DateTimeFormat('en-US', {
    year: 'numeric',
    month: 'numeric',
    day: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
    second: 'numeric',
    hour12: false,
  }).format(date);

export const formatMonth = (date) =>
  new Intl.DateTimeFormat('en-US', {
    month: 'long',
  }).format(date);

Fortunately JavaScript's Intl API gives us excellent tools for date conversions. However, instead of using the API directly in my React components, I like to have a service for it, because only this way I can guarantee that my components have only a little set of actively used date formatting options available for my application.

Now it's possible to not only import each date formatting function individually:

import { formatMonth } from '../../services/format/date';

const month = formatMonth(new Date());

But also as a service, as an encapsulated module in other words, what I usually like to do:

import * as dateService from '../../services/format/date';

const month = dateService.formatMonth(new Date());

It may become difficult to import things with relative paths now. Therefore I always would opt-in Babel's Module Resolver for aliases. Afterward, your import may look like the following:

import * as dateService from 'format/date';

const month = dateService.formatMonth(new Date());

After all, I like this technical separation of concerns, because it gives every folder a dedicated purpose and it encourages sharing functionality across the React application.

FEATURE FOLDERS

The last step will help you to structure large React applications, because it separates specific feature related components from generic UI components. While the former are often only used once in a React project, the latter are UI components which are used by more than one component.

I'll focus on components here, for the sake of keeping the example small, however, the same learnings can be applied to other technical folders from the previous section. Take the following folder structure as example, which may not show the full extent of the problem, but I hope you get the point:

- src/
--- components/
----- App/
----- List/
----- Input/
----- Button/
----- Checkbox/
----- Radio/
----- Dropdown/
----- Profile/
----- Avatar/
----- MessageItem/
----- MessageList/
----- PaymentForm/
----- PaymentWizard/
----- ErrorMessage/
----- ErrorBoundary/

The point: There will be too many components in your components/ eventually. While some of them are reusable (e.g. Button), others are more feature related (e.g. Message).

From here, I would use the components/ folder only for reusable components (e.g. UI components). Every other component should move to a respective feature folder. The names of the folders are again up to you:

- src/
--- feature/
----- User/
------- Profile/
------- Avatar/
----- Message/
------- MessageItem/
------- MessageList/
----- Payment/
------- PaymentForm/
------- PaymentWizard/
----- Error/
------- ErrorMessage/
------- ErrorBoundary/
--- components/
----- App/
----- List/
----- Input/
----- Button/
----- Checkbox/
----- Radio/
----- Dropdown/

If one of the feature components (e.g. MessageItem, PaymentForm) need access to shared Checkbox, Radio or Dropdown component, it imports it from the reusable UI components folder. If a domain specific MessageList component needs an abstract List component, it imports it as well.

Furthermore, if a service from the previous section is tightly coupled to a feature, then move the service to the specific feature folder. The same may apply to other folders which were previously separated by technical concern:

- src/
--- feature/
----- User/
------- Profile/
------- Avatar/
----- Message/
------- MessageItem/
------- MessageList/
----- Payment/
------- PaymentForm/
------- PaymentWizard/
------- services/
--------- Currency/
----------- index.js
----------- service.js
----------- test.js
----- Error/
------- ErrorMessage/
------- ErrorBoundary/
------- services/
--------- ErrorTracking/
----------- index.js
----------- service.js
----------- test.js
--- components/
--- hooks/
--- context/
--- services/
----- Format/
------- Date/
--------- index.js
--------- service.js
--------- test.js

Whether there should be an intermediate services/ folder in each feature folder is up to you. You could also leave out the folder and put the ErrorTracking/ folder directly into Error/. However, this may be confusing, because ErrorTracking should be marked somehow as a service and not as a React component.

There is lots of room for your personal touch here. After all, this step is just about bringing the features together which allows teams in your company to work on specific features without having to touch files across the project.

BONUS: FOLDER/FILE NAMING CONVENTIONS

Before we had component-based UI libraries like React.js, we were used to name all of our folders and files with a kebab-case naming convention. In a Node.js world, this is still the status quo naming conventions. However, on the frontend with component-based UI libraries, this naming convention changed to PascalCase for folders/files containing components, because when declaring a component it follows a PascalCase naming convention as well.

- src/
--- feature/
----- user/
------- profile/
------- avatar/
----- message/
------- message-item/
------- message-list/
----- payment/
------- payment-form/
------- payment-wizard/
----- error/
------- error-message/
------- error-boundary/
--- components/
----- app/
----- list/
----- input/
----- button/
----- checkbox/
----- radio/
----- dropdown/

Like in the example above, in a perfect world, we would be using a kebab-case naming convention for all folders and files, because PascalCase named folders/files are handled differently in the diversity of operating systems which may lead to bugs when working with teams using different OSs.

BONUS: NEXT.JS PROJECT STRUCTURE

A Next.js project starts with a pages/ folder. A common question here: Where to put the src/ folder?

- api/
- pages/
- src/
--- feature/
--- components/

Usually the source folder gets created next to the pages folder. From there, you can follow the previously discussed folder/file structure within the src/ folder. I heard about an escape hatch in Next.js where you can put the pages/ folder in the src/ folder too:

- api/
- src/
--- pages/
--- feature/
--- components/

However, in this case it's not allowed to have a pages/ folder anymore.

Having all this written, I hope it helps one or the other person or team structuring their React project. Keep in mind that none of the shown approaches is set in stone. In contrast, I encourage you to apply your personal touch to it. Since every React project grows in size over time, most of the folder structures evolve very naturally as well. Hence the 5 step process to give you some guidance if things get out of hand.


Understanding Folder Structure For React Project

In this tutorial, we will understand and see the folder structure of basic React app.

Creating React applications

We will try to create react application using command line.

Step 1

Open command prompt and go to the directory where you want to create your first react js application using below command

cd <directoryName> (example cd Desktop) If you want to create app on desktop

Step 2

Create react project with below command. Hellowreact is the name of project/folder. It will install all dependencies as well.

npx create-react-app hellowreact

Once done you will see below information in terminal widow. It means your first project has been created and you are ready to use it.

Open project using code editor Visual Studio Code.

https://www.c-sharpcorner.com/article/how-to-get-started-with-react-js/

Click on Open folder and go to the folder where project got created.

Select the folder and it will open in VS Code editor.

How to run React JS project

Click on “Terminal” menu in VS code and go to “New Terminal” submenu.

Terminal -> New Terminal

A terminal will get open with project path.

Understand Folder Structure for React project

Type “npm start” in command terminal and it will open browser with localhost://3000 port.

Understand Folder Structure for React project

Folder Structure

The React application automatically creates required folders, as shown below.

node_modules

This folder will contain all react js dependencies.

.gitignore

This file is used by source control tool to identify which files and folders should be included or ignored during code commit

package.json

This file contains dependencies and scripts required for the project.

Understand Folder Structure for React project

Src folder

src is one of the main folder in react project.

Understand Folder Structure for React project

Index.js

index.js is the file that will be called once we will run the project.

App.js

App.js is a component that will get loaded under index.js file. If we do any change in app.js file HTML component and save it it will reflect in localhost://3000

Understand Folder Structure for React project

Understand Folder Structure for React project

Summary

In this article, we have learned how to create a React app using create-react-app and then see the folder structure of basic react app.

#reactjs #react #javascript #programming #webdev 

How to Folder Structure from Small to Large React Projects
Vinnie  Erdman

Vinnie Erdman

1656462780

Movie Website in React JS in Hindi #7: Search Bar Functionality in React JS

How to Create Search Bar Functionality for Movie Website in React JS

♥ Free Source Code Link: https://www.thapatechnical.com/2022/06/movie-website-in-react-js.html

0:00 Intro
0:50 Giveaway
1:30 Search Func. Explained
2:10 State Management
4:10 Search Func. Code
9:30 Search Code Review
10:30 Outro

#react #reactjs

Movie Website in React JS in Hindi #7:  Search Bar Functionality in React JS
Vinnie  Erdman

Vinnie Erdman

1656455520

How to Secure Private Data with .ENV for Movie Website in React JS

Welcome, Movie Website in React JS in Hindi #6: How to secure our private data from outsiders with .ENV file. Yes, it's true, we need to hide our private keys, personal information on website so that no one can misuse it, so for that reason only we need to hide or protect our data and for that we have .env file.

And rest what is .env file and how it secure our data? To know all these you need to watch the video♥

♥ Free Source Code Link: https://www.thapatechnical.com/2022/06/movie-website-in-react-js.html

-------------- Timeline ---------------
0:00 Intro & Brief
1:15 create .env file
1:45 create .env variable 
3:00 hiding .env file
4:01 access .env var. 
6:10 Shortend Movie Title 
7:00 GiveAway
7:45 JS Substring
9:05 JS Title Condition
11:50 Video Review
12:20 Outro

#react #reactjs

How to Secure Private Data with .ENV for Movie Website in React JS
Vinnie  Erdman

Vinnie Erdman

1656448200

How to Create Movie Page with UI using JSX CSS in React JS

Welcome, Movie Website in React JS in Hindi #5:  Render JSX (HTML), Include CSS with Media Queries. We will create our movie page with a complete user interface using JSX and CSS.

♥ Free Source Code Link: https://www.thapatechnical.com/2022/06/movie-website-in-react-js.html

------------ Timeline --------------
0:00 Intro
1:14 JSX UI
6:35 CSS Part
7:12 GiveAway
7:55 CSS Explained
9:00 Import CSS File
9:25 CSS Hover & Animation
10:40 Website Responsive
11:07 Free Source Code
11:50 Key Prop in Map
12:30 Outro

#html #css #react  #reactjs 

How to Create Movie Page with UI using JSX CSS in React JS
Roscoe  Batz

Roscoe Batz

1656446400

How to Create Bar Chart in React using React-Chartjs-2

In this video we will build a bar chart in React using react-chartjs-2 npm package and we will send the data for the chart from our Node js / Express server using an API route and fetch

Hope you will like and enjoy.

Here's a git repo: https://github.com/marinakim44/charts

#reactjs  #chartjs  #nodejs  #javascript 

How to Create Bar Chart in React using React-Chartjs-2
Vinnie  Erdman

Vinnie Erdman

1656440940

How to Render State Manage for Movie Website in React JS

In this video tutorial, We''ll share How to Render Movie API & How to State Management for Movie Website in React JS.

♥ Free Source Code Link: https://www.thapatechnical.com/2022/06/movie-website-in-react-js.html

#react #reactjs

How to Render State Manage for Movie Website in React JS
Vinnie  Erdman

Vinnie Erdman

1656440820

How to Use Context API & UseContext Hook for Movie Website in React JS

Welcome, we will create a context file and use context API, and usecontext hook to pass the data from parent to child component. Also, we will create a custom useGlobalContext to make proper use of useContext hook.

♥ Free Source Code Link: https://www.thapatechnical.com/2022/06/movie-website-in-react-js.html

#react #reactjs

How to Use Context API & UseContext Hook for Movie Website in React JS