LoginSignup
0
0

More than 1 year has passed since last update.

React Qiita API から記事情報を取得して表示させる

Posted at

ReactのAPI練習用に。

index.js
import React from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import Search from "./Search";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      postsList: []
    };

    this.handleClick = this.handleClick.bind(this);
    this.renderImageList = this.renderImageList.bind(this);
  }

  handleClick(target) {
    const search = target;
    const limit = 20;
    const url = `https://qiita.com/api/v2/items?page=1&per_page=${limit}&query=${search}`;
    axios
      .get(url, {
        headers: {
          Authorization: "Bearer 0a499cd45f8b05c01ec95e4b852f6e91d0dfff44"
        }
      })
      .then((res) => {
        this.setState({ postsList: res.data });
      })
      .catch(console.error);
  }

  renderImageList(list) {
    const posts = list.map((item, index) => {
      return (
        <li className="item" key={index}>
          <span>{index}: </span>
          <a href={item.url}>{item.title}</a>
        </li>
      );
    });
    return posts;
  }

  render() {
    return (
      <div>
        <Search search={this.handleClick} />
        <ul>{this.renderImageList(this.state.postsList)}</ul>
      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Search.js

import React from "react";

class Search extends React.Component {
  constructor(props) {
    super(props);
    this.state = { title: "" };
  }

  render() {
    return (
      <div>
        <h2>Find Qiita</h2>
        <form onSubmit={this.handleSubmit}>
          <input
            value={this.state.title}
            type="text"
            onChange={this.handleChange}
          />
          <input type="submit" value="Search" />
        </form>
      </div>
    );
  }

  // valueが変更された際に実行
  handleChange = (event) => {
    // 変更したvalueが返ってくる
    const title = event.target.value;
    // stateを変更
    this.setState({ title: title });
  };

  // submitされた際に実行
  handleSubmit = (event) => {
    event.preventDefault(); // ページ遷移防止
    // 受け取ったメソッドを実行し、app の state を変更している
    this.props.search(this.state.title);
    this.setState({ title: "" }); // submit後は、titleを空にする
  };
}
export default Search;


スクリーンショット 2021-05-27 16.52.40.png

0
0
0

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
0
0