0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

React – フォームを使って axiosでPOSTリクエストする ( + radio で選択する )

Last updated at Posted at 2023-01-09

httpbinはPOSTしたリクエスト内容に応じてレスポンスをJSONを返してくれるので、そのレスポンスを画面に表示する

コード例

example.tsx


import './App.scss';
import axios from "axios";

import { useForm } from "react-hook-form";
import { useState } from 'react'

const Example = () => {
  const { register, handleSubmit } = useForm();

  const items = ["item1", "item2", "item3", "item4"]
  const [val, setVal] = useState('item1');

  const requestURL = "https://httpbin.org/post";
  const [getData, setResponse] = useState({ form: { content: "", item: "" }});

  const onSubmit = (data: any) => {
    axios.post(requestURL, new URLSearchParams(data)).then((response) => {
      setResponse(response.data);
    });
  };
  const handleChange = (e: any) => {
    setVal(e.target.value);
  };

  return (
    <div className="App">
      <h1>POST</h1>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div>
          <label htmlFor="content">content</label>
          <input id="content" {...register('content')} />
        </div>
        <div>
        </div>
        {items.map((item) => {
          return (
            <div key={item}>
              <input
                id={item}
                type="radio"
                {...register('item')}
                value={item}
                onChange={handleChange}
                checked={item === val}
              />
              <label htmlFor={item}>{item}</label>
            </div>
          );
        })}
        <button type="submit">Submit</button>
      </form>
      <div>
        <h2>Content</h2>
          <p>{getData['form']['content']}</p>
        <h2>Item</h2>
          <p>{getData['form']['item']}</p>
      </div>
    </div>

  );
}

export default Example;

実行例

画面上がフォーム
画面下でhttpbinからの応答一部を表示している

image

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?