Home > Software design >  How do I implement the select option using Typescript in React app?
How do I implement the select option using Typescript in React app?

Time:10-10

I am quite new and am trying to allow user to select multiple color selections which will be stored in the backend as strings after submission. However, the error is telling me "ChangeEventHandler" is not applicable to select types.

This is the parent component:

import React, { MouseEvent, useState, ChangeEvent, FormEvent } from "react";
import InputForm from "./InputForm";
import { useNavigate } from "react-router-dom";
import axios from "axios";

export default function Form() {
  const [color, setColor] = useState("");
  const navigate = useNavigate();

  const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
    switch (event.target.name) {
      case "color":
        setName(event.target.value);
        break;
      default:
    }
  };

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    await axios
      .post(`http://localhost:3000`, {
        color,
      })
  };

  return (
    <div>
        //handleChange and handleSubmit has errors here
        <InputForm color={color} handleChange={handleChange} handleSubmit={handleSubmit}/>
    </div>
  );
};

Here is my child component that renders out the selection page.

interface Colors {
  color: string;
  handleChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  handleSubmit: (e: React.FormEvent<HTMLFormElement>) => void;
}

export default function InputForm({ color, handleChange, handleSubmit }: Colors) {
  return (
    <div>
      <form onSubmit={handleSubmit}>
        <label placeholder="name">Colors</label>
        <select
          type="text"
          placeholder="Blue"
          name="color"
          value={color}
          onChange={handleChange}
        >
          <option value="Red">Red</option>
          <option value="Yellow">Yellow</option>
          <option value="Green">Green</option>
          <option value="Green">Black</option>
        </select>
      </form>
    </div>
  );
}

How do I implement the multiple selection component? Thank you.

CodePudding user response:

You need ChangeEvent<HTMLSelectElement> instead of ChangeEvent<HTMLInputElement> in each instance it appears. The latter is only for <input> elements.

CodePudding user response:

You can use mantine, it is a very useful library extra, you can play as you want with the style part.

https://v4.mantine.dev/core/multi-select/

You can also track your own mouse movement this way.

https://v4.mantine.dev/hooks/use-mouse/

  • Related