LoginSignup
44
34

More than 3 years have passed since last update.

ReactでQiitaAPIを叩いてアプリを作る入門

Last updated at Posted at 2019-08-29

はじめに

Reactの勉強を始めたので手始めにAPIを叩いて超簡単なアプリを一から作ってみる練習をしました。
今回使用したAPIはQiita API v2です。作成したアプリはGitHubのリポジトリにあげてあります。

どのAPIを叩くか決めるとき参考にした記事
https://qiita.com/mikan3rd/items/ba4737023f08bb2ca161
アプリを作るときに参考にした記事
https://qiita.com/gcyagyu/items/4d186df2e90c53228951

create-react-appでプロジェクトの作成

create-react-appを使うことでアプリの雛形を作ることができます。今回はreact-api-studyというアプリ名で作成しています。

参考
https://create-react-app.dev/

$ create-react-app react-api-study

axiosのインストール

アプリを作成したらディレクトリを移動して、axiosをインストールします。

$ cd react-api-study
$ yarn add axios

アプリの実装

今回はQiitaAPIのhttps://qiita.com/api/v2/itemsのエンドポイントを叩いて記事一覧を取ってきて、タイトルとURLを表示させます。

GET /api/v2/items
記事の一覧を作成日時の降順で返します。

  • page
    • ページ番号 (1から100まで)
    • Example: 1
    • Type: string
    • Pattern: /^[0-9]+$/
  • per_page
    • 1ページあたりに含まれる要素数 (1から100まで)
    • Example: 20
    • Type: string
    • Pattern: /^[0-9]+$/
  • query
    • 検索クエリ
    • Example: "qiita user:yaotti"
    • Type: string

src/index.jsの拡張子を変えてsrc/index.jsxを記述します

src/index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

// 次に記述する src/components/App.jsx をインポートする
import App from './components/App';

ReactDOM.render(<App />, document.getElementById('root'));

srcディレクトリの下にcomponentsディレクトリを作成し、その中にApp.jsxファイルを作成し次のソースを記述します。

src/components/App.jsx
import React, { Component } from 'react';
// axiosをインポート
import axios from 'axios';

class App extends Component {
  constructor(props) {
    super(props);
    this.getQiitaPosts = this.getQiitaPosts.bind(this);
    this.state = {
      // ここを`React`など検索したいワードに変えられる
      query: 'React'
    }
  }

  // QiitaAPIを叩く
  getQiitaPosts() {
    //axios.get(APIのエンドポイント,パラメータの引数)
    axios.get('https://qiita.com/api/v2/items', {
        params: {
          "page": "1",
          "per_page": "20",
          "query": this.state.query,
        }
      })
      // response にAPIからのレスポンスが格納される
      .then((response) => {
        // data にレスポンスから帰ってきた1つ目の記事の情報を格納
        const data = response.data[0];
        this.setState({
          title: data.title,
          url: data.url,
        });
        // コンソールから response と title と url を確認
        console.debug(response, "ressponse");
        console.debug(this.state.title, "title")
        console.debug(this.state.url, "url")
      })
      .catch((error) => {
        console.debug(error);
      });
  }

  // 表示されるHTMLを記述
  render() {
    return (
      <div className="App">
        <h1 className="app-title">Hello Qiita API</h1>
        <p>タイトル: {this.state.title}</p>
        <p>URL: <a target="__blank" href={this.state.url}>{this.state.url}</a></p>
        <input
          type="button"
          value="検索"
          onClick={() => this.getQiitaPosts()}
        />
      </div>
    )
  }
}

export default App;

{this.state.title}などでAPIから取ってきた値を埋め込んで表示させています。
<a target="__brank" href={this.state.url}>aタグのhref属性にurlを指定してリンクを埋め込んでいます。
onClick={() => this.getQiitaPosts()}で検索ボタンをクリックしたときにQiitaAPIを叩く関数を呼び出しています。

完成

ターミナルでnpm startで起動してlocalhost:3000を開きます

検索ボタンを押したあとの画面
スクリーンショット 2019-08-29 12.19.04.png

おわりに

間違っていることや改善したほうが良いことがあればコメントで優しく教えて下さいmm

44
34
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
44
34