creativetimofficial / material-tailwind

@material-tailwind is an easy-to-use components library for Tailwind CSS and Material Design.
https://material-tailwind.com/
MIT License
3.81k stars 321 forks source link

Get the Select name #305

Open Barno opened 1 year ago

Barno commented 1 year ago

I'd like to understand how to retrieve the Select name.

My component is (partial)

const [inputs, setInputs] = useState();
const handleChange = (e) => {    
    setInputs((prev) => ({ ...prev, [e.target.name]: e.target.value }));
  };
<Select
            type="string"
            label="kind"
            size="lg"
            name="kind"
            required
            onChange={(value) => handleChange(value)}
          >

            {
              Object.keys(kind).map((key) => (
                <Option key={key} value={key}>
                  {key}
                </Option>
              ))
            }
</Select>

but I got an error, because onChange return only the value selected. The Select rendered as button and ul li

I create this workaround but it's not a good solution

 <Select
            type="string"
            label="kind"
            size="lg"
            name="kind"
            required
            onChange={(value) => handleChange("kind-" + value)}
          >

            {
              Object.keys(kind).map((key) => (
                <Option key={key} value={key}>
                  {key}
                </Option>
              ))
            }

          </Select>

  const handleChange = (e) => {
    let name
    let value
    console.log(e)
    if (typeof e === "object" && e !== null) {
      name = e.target.name;
      value = e.target.value;
    } else {
      let parts = e.split("-");
      name = parts[0]
      value = parts[1]     
    }

    setInputs((prev) => ({ ...prev, [name]: value }))

  };

is it possible to retrieve ,e.target.name, e.target.value?

GanatraJay2000 commented 1 year ago

Hi, same here, why is the Select component rendered as a button, ul, li, and even if it is rendered as such why does onChange return a string and not an event? Please help. I'm trying to work with React Hook Forms (register & controller).