LoginSignup
0
0

More than 1 year has passed since last update.

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

Posted at

コード例

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オープンチャットもご利用ください。

Twitter

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