🖥

React (Next.js) – radioボタン + onChange で送信ボタンを押さずにaxiosリクエストする

2023/09/01に公開

コード例

import axios from "axios";
import { useState } from 'react'

const RadioChangePost = () => {
  const [val, setVal] = useState('');
  const requestURL = "https://httpbin.org/post";
  const [gotResponse, setResponse] = useState({ "form": { item: "" }});

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

  return (
    <>
      <div>
        <input
          type="radio"
          value="heat"
          onChange={HeatHandleChange}
          checked={val === 'heat'}
        />
        Heat
      </div>
      <div>
        <input
          type="radio"
          value="cool"
          onChange={HeatHandleChange}
          checked={val === 'cool'}
        />
        Cool
      </div>
      <div>{gotResponse['form']["item"]}</div>
    </>
  );
}
export default RadioChangePost;

動作例

image

環境

  • react@18.2.0
  • next@13.1.1

チャットメンバー募集

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

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2023-01-10

Discussion