0
0

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 で画像を選択するradio box のフォームを作ってaxiosでPOSTリクエストする

Last updated at Posted at 2023-01-09

コード例

radioで選んだ値をuseStateの値として保持しておいて、axios通信時に利用している
CSSだけでやりくりするのが難しかったため

ImageRadio.tsx

import axios from "axios";
import ImageRadioCss from "./ImageRadio.module.css";

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

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

  const items = ["item1", "item2"]
  const [selectedItem, setItem] = useState("");

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

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

  return (
    <div className="App">
      <h1>Form ImageRadio</h1>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div>
        </div>
        {items.map((item) => {
          return (
            <div key={item}>
              <input
                className={ImageRadioCss["item-input"]}
                id={item}
                type="radio"
                {...register('item')}
                value={item}
                onChange={handleChange}
                checked={item === selectedItem}
              />
              <label
                htmlFor={item}

                className={ImageRadioCss[item]}
              >
              </label>
            </div>
          );
        })}
        <button type="submit">Submit</button>
      </form>
      <div>
        <h2>Item</h2>
        <p>{getData['form']['item']}</p>
      </div>
    </div>

  );
}

export default Form;

ImageRadio.module.css


/* item1 / item2 のプロパティは共通化してない */
.item1 {
  content: "";
  display: inline-block;
  background-size: contain;
  width: 100px;
  height: 60px;
  background-image: url(./images/1.png);
}

.item2 {
  content: "";
  display: inline-block;
  background-size: contain;
  width: 100px;
  height: 60px;
  background-image: url(./images/2.png);
}

.item-input:checked + label {
  border: 5px solid red;
  box-sizing: border-box;
}
.item-input {
  display:none;
}

動作例

image

環境

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?