どのように反応を使用して引用共有アプリケーションを構築する.の反応を共有し、反応


引用共有アプリケーションは、APIから引用符とその著者のリストを取得し、ワンクリックであなたのソーシャルメディアにこれらの引用符を共有することができますWebアプリケーションです.このアプリケーションを構築することにより、どのように反応Paginateを使用してデータをページ化する方法を学び、また、反応共有を使用してWebアプリケーションにソーシャルメディアの共有ボタンを統合します.
プレビューライブデモQuotweet
React-share あなたのWebアプリケーションにソーシャルメディアの共有ボタンを埋め込むことができるライブラリです.これは、数多くの社会的なメディアのアイコンが含まれてもカスタムアイコンをサポートしています.
React-paginate データをページ化するために使用されるreactjsコンポーネントです.それは自動的には、いくつかの小道具を渡すときにデータを移動するために使用されるナビゲーションバーを作成します.それはあなたがバニラCSSまたはあなたが好む任意のCSSフレームワークを使用して任意の方法をナビゲーションバーをスタイルすることができます非常に柔軟なライブラリです.

This article requires a basic understanding of working with APIs in React.js.




プロジェクトのセットアップとインストール


このWebアプリケーションを構築するには、Create Reactionアプリをインストールし、共有する反応とPaginateを反応させる必要があります.
🚀 端末を開く
🚀 以下のコードを実行することによって、アプリケーションを作成します.
npx create-react-app@latest quotweet
🚀 以下のコードを実行して、反応共有をインストールします
npm install react-share --save
🚀 次のコードを端末で実行することで、PageGateを追加します.
npm install react-paginate --save
🚀 開発サーバーを起動します.あなたがtailwind cssを使用していないならば、あなたは次のセクション
npm start
🚀 オプション:以下のコマンドを実行して、Cookieをインストールします.Coodernユーザーインターフェイスを構築するためのユーティリティの最初のCSSフレームワークです.
  npm install -D tailwindcss postcss autoprefixer
🚀 風車を作る.設定.JSとPostcss .設定.実行中の設定ファイル
npx tailwindcss init -p
🚀 オープンtailwind.config.js 次のコードをコピーします.
module.exports = {
  content: ['./src/**/*.{js,jsx,ts,tsx}'],
  theme: {
    extend: {},
  },
  plugins: [],
};
🚀 に./src/index.css ファイルを追加します.
@tailwind base;
@tailwind components;
@tailwind utilities;

プロジェクト概要


🚀 オープンApp.js 以下のコードをファイルとコピーします.
function App() {
  return (
    <div>
      <Header />
      <Quotes />
      <Pagination />
    </div>
  );
}

export default App;

From the code snippet above, I divided the web application into three components: headers, quotes, and a pagination bar.


🚀 クリエイトアcomponents フォルダ内の各コンポーネントを作成します.

ヘッダーコンポーネントの構築


これには、Webアプリケーションやその他の機能のタイトルが含まれます.
🚀 オープンHeader.js Webアプリケーションのメニューバーを作成します.次のコードスニペットをコピーできます.
import React from 'react';

const Header = () => {
  return (
    <header className="w-full h-[10vh] bg-[#1DA1F2] flex flex-col items-center justify-center mb-8 sticky top-0 z-50">
      <h3 className="text-2xl text-[#f7f7f7]">Quotweet</h3>
    </header>
  );
};

export default Header;

APIと状態管理からデータを取得する方法


引用符のURLです"https://api.quotable.io/quotes" そして作者は"https://images.quotable.dev/profile/200/${authorSlug}.jpg" . 作者のURLはauthorSlug そのイメージを得るパラメータとして.

In order to make this tutorial simple and easy to follow, all state management will be done in App.js then the values will be passed down to other components as props.


エディットApp.js 次の通り
import Pagination from './components/Pagination';
import Quotes from './components/Quotes';
import Header from './components/Header';
import { useState, useEffect } from 'react';

function App() {
  const [quotes, setQuotes] = useState([]);  //contains the quotes - array of objects
  const [loading, setLoading] = useState(true);  - //boolean value for checking whether the quotes are available

  const fetchQuotes = () => {
    fetch('https://api.quotable.io/quotes') //URL for fetching all the available quotes
      .then((data) => data.json())
      .then((res) => {
        setQuotes(res.results);
        setLoading(false)
      });
  };

  useEffect(() => {
    fetchQuotes();
  }, []);

  return (
    <div className="w-full min-h-screen">
      <Header />
      {loading ? <p>Loading</p> : <Quotes quotes={quotes} />}
      <Pagination/>
    </div>
  );
}

export default App;
  • 上のコードスニペットから.
  • 私は2つの州を作りましたquotes 引用符の配列とloading データが利用可能な場合にクォートコンポーネントを切り替えます.
  • fetchQuotes 関数は、API URLがページ内のクォートを返します(ページあたり20ページ)、その後、setQuotes 引用符を状態と変更に保存するにはsetLoading 嘘をつく.
  • If the loading 状態はtrueです-内容がまだ利用できないということを意味して、それはユーザーへのローディングを示します、そして、それが利用できるとき、それはQuotes コンポーネント.
  • 引用符コンポーネントの構築


    このコンポーネントは、APIから取得されたすべての引用符を含んでいます.
    import React from 'react';
    import QuoteCard from './QuoteCard';
    
    const Quotes = ({ quotes }) => {
      return (
        <main className="w-full flex item-center p-4 flex-wrap gap-6 justify-center max-w-[1500px] min-h-screen">
          {quotes.map((quote) => (
            <QuoteCard quote={quote} key={quote._id} />
          ))}
        </main>
      );
    };
    
    export default Quotes;
    
  • 上のコードスニペットから
  • The Quotes コンポーネントはpropを受け入れるquotes - は、App.js .
  • 私はQuoteCard 各引用符の構造を表すコンポーネント.その後、各引用符を介してレンダリングされますQuoteCard クォートの配列をマッピングするコンポーネント.
  • コンポーネントの構築


    これは引用符の表示方法を示すコンポーネントです.
    import React from 'react';
    
    const QuoteCard = ({ quote }) => {
      return (
        <div className="w-[90%] bg-gray-50 sm:w-[300px] rounded-xl  shadow hover:bg-gray-100 flex-col items-center justify-center p-4 text-center">
          <div className="w-full flex items-center justify-center mb-6">
            <img
              src={`https://images.quotable.dev/profile/200/${quote.authorSlug}.jpg`}
              alt={quote.author}
              className="w-[100px] rounded-full"
            />
          </div>
    
          <div>
            <h3>{quote.author}</h3>
            <p className="opacity-40">{quote.content}</p>
          </div>
        </div>
      );
    };
    
    export default QuoteCard;
    
  • 上のコードスニペットから.
  • コンポーネントは、各引用符を受信し、レイアウトに応じて表示されます.
  • イメージタグには、ソース属性に含まれるURLを使用してイメージも表示されます.著者の名前と引用も表示されます.

  • どのように反応共有を使用してTwitterの共有ボタンを追加する


    我々は、APIから正常に引用符とその画像を取得することができたので、プロジェクトにTwitterの共有ボタンを追加しましょう.
    エディットQuoteCard コンポーネント
    import React from 'react';
    import { TwitterIcon, TwitterShareButton } from 'react-share'; //necessary import
    
    const QuoteCard = ({ quote }) => {
      return (
        <div className="w-[90%] bg-gray-50 sm:w-[300px] rounded-xl  shadow hover:bg-gray-100 flex-col items-center justify-center p-4 text-center">
          <div className="w-full flex items-center justify-center mb-6">
            <img
              src={`https://images.quotable.dev/profile/200/${quote.authorSlug}.jpg`}
              alt={quote.author}
              className="w-[100px] rounded-full"
            />
          </div>
    
          <div>
            <h3>{quote.author}</h3>
            <p className="opacity-40">{quote.content}</p>
          </div>
    
          {/* ----- changes made ---- */}
          <div className="icons w-full p-4 flex items-center justify-end">
            <TwitterShareButton
              title={`"${quote.content}" - ${quote.author}`}
              url={'https://twitter.com'}
              via={'Arshadayvid'}
              hashtags={['30DaysOfCode', 'javascript']}
            >
              <TwitterIcon
                size={32}
                round={true}
                className="opacity-40 cursor-pointer hover:opacity-100"
              />
            </TwitterShareButton>
          </div>
          {/* ----- end of react-share ---- */}
        </div>
      );
    };
    
    export default QuoteCard;
    
  • 上のコードスニペットから.
  • 私はインポートTwitterIcon - Twitterの公式アイコンを提供していますTwitterShareButton - これは、反応共有からTwitterの機能を介して共有を提供します.
  • TwitterShareButton ラップするTwitterIcon コンポーネントとそれはまた、タイトル、URL、およびハッシュのようないくつかの小道具を受け取ります.タイトルは、共有するコンテンツを表すURLは、Twitterのホームページのリンクは、オプションであり、Twitterの言及のために使用され、ハッシュタグは、各共有に追加するTwitterのハッシュタグを表します.
  • TwitterIcon また、サイズやラウンドのような小道具を受け入れる.
  • Paginationを使用したページ付けの追加


    Paginateは非常に使いやすい柔軟なコンポーネントです.
    🚀 オープンユアPagination.js ファイル.
    🚀 エディットApp.js
    import Pagination from './components/Pagination';
    import Quotes from './components/Quotes';
    import Header from './components/Header';
    import { useState, useEffect } from 'react';
    
    function App() {
      const [quotes, setQuotes] = useState([]);
      const [totalPages, setTotalPages] = useState(null);
      const [loading, setLoading] = useState(true);
    
      const fetchQuoteTexts = () => {
        fetch('https://api.quotable.io/quotes')
          .then((data) => data.json())
          .then((res) => {
            setTotalPages(res.totalPages);
            setQuotes(res.results);
            setLoading(false);
          });
      };
      useEffect(() => {
        fetchQuoteTexts();
      }, []);
      return (
        <div className="w-full min-h-screen">
          <Header />
          {loading ? <p>Loading</p> : <Quotes quotes={quotes} />}
    
          <Pagination
            totalPages={totalPages}
            setQuotes={setQuotes}
            setLoading={setLoading}
          />
        </div>
      );
    }
    
    export default App;
    
  • 上のコードスニペットから
  • 私は、利用可能なページの総数を保持する状態を作成し、一度データが利用できると、状態の値はAPIから取得したページの総数に変更されます.
  • ページネーションアクセプトtotalPages , setQuotes and setLoading 小道具として.
  • 🚀 にPagination.js ファイルには、次のコードがあります.
    import React from 'react';
    import ReactPaginate from 'react-paginate';
    
    function Pagination({ totalPages, setQuotes, setLoading }) {
      const handlePageClick = (data) => {
        const pageNumber = data.selected + 1;
        const fetchData = async () => {
          fetch(`https://api.quotable.io/quotes?page=${pageNumber}`)
            .then((data) => data.json())
            .then((res) => {
              setQuotes(res.results);
              setLoading(false);
            });
        };
        fetchData();
      };
    
      return (
        <div className="w-full items-center justify-center mx-auto">
          <ReactPaginate
            breakLabel="..."
            nextLabel=">>>"
            previousLabel="<<<"
            onPageChange={handlePageClick}
            pageRangeDisplayed={2}
            marginPagesDisplayed={1}
            pageCount={totalPages}
            renderOnZeroPageCount={null}
            containerClassName="sm:py-4 sm:px-6 p-2 border-2 mt-8 flex items-center justify-center w-2/3 mx-auto mb-10 shadow-lg"
            pageLinkClassName="sm:py-4 sm:px-6 p-2 bg-white"
            previousLinkClassName="sm:py-4 sm:px-6 p-2 bg-white"
            nextLinkClassName="sm:py-4 sm:px-6 p-2 bg-white"
            breakLinkClassName="sm:py-4 sm:px-6 p-2 bg-white"
            activeLinkClassName="bg-blue-100"
          />
        </div>
      );
    }
    
    export default Pagination;
    
  • 上のコードスニペットから.
  • ReactPaginate ナビゲーションバーを表示するパッケージからインポートされました.
  • The breakLabel , previousLabel , and nextLabel ブレーク、次と前のボタンの値を表します.
  • onPageChange が含まれます.handlePageClick ページが変更されたときに呼び出され、ボタンの正確な値をクリックします.
  • 機能handlePageClick ナビゲーションアイコンのインデックスをクリックし、APIで使用可能なデータを取得する値に1を追加します.
  • で終わる小道具ClassName スタイルのボタンをあなたがそれらを任意の方法を有効にします.
  • pageCount ページからの小道具としてのページの総数を受け入れますApp.js . この値が必要です.
  • pageRangeDisplayed ページの範囲が表示されます.
    訪問するdocumentation 詳細は
  • 結論


    反応共有と反応Paginateは、あなたがあなたのウェブアプリケーションに加えることができる2つの小さな図書館です.
    これは初心者にやさしいプロジェクトです.
  • 認証の追加
  • 別のAPIを使用して、おそらく冗談のAPIは、人々は彼らの社会的なメディアのハンドルに面白い発見ジョークを共有することができます.
  • 他のソーシャルメディア共有機能の追加
  • コピーと貼り付け機能の追加
  • 任意の状態管理ライブラリを使用して- redux、mobxなど.
  • 設計とユーザインタフェースの改善
  • これまで読んでくれてありがとう!

    資源


    APIドキュメントhttps://github.com/lukePeavey/quotable
    イメージURLhttps://images.quotable.dev/profile/200/${authorSlug}.jpg
    引用URLhttps://api.quotable.io/quotes
    生のデモhttps://quotweet.vercel.app
    これについてアクションボタン
    背景色:1 .重要
    色:1 .重要
    ボーダーカラー:C .重要


    デビッド・アサロ


    I write and share thoughts on web development ⭐ | Frontend Developer (React.js) ✅

    作家の角


    こんにちは、私はフリーランスの技術的な書き込みのギグとリモートの機会にオープンです.一緒に働きましょう.📧: [email protected]
    お気軽に私と接続して