Home > Mobile >  How to handle multiple select options submittion in react js?
How to handle multiple select options submittion in react js?

Time:12-06

I want to submit a form into mongoDB using nodejs API & reactJs. With the exception of the multiple select option, everything is operating as it should be.

Being new to react, I have no idea how to handle the multi select option's onChange method.

Here is what I've tried:

import React, { useState, useRef } from "react";
import { useForm } from "react-hook-form";
import { v4 as uuidv4 } from 'uuid';
import axios from "axios";
import Select from 'react-select';

export default function EventForm(props) {

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm();
  const form = useRef();
  const [loading, setLoading] = useState(false);

  const [info, setInfo] = useState("");
  const [analysis, setAnalysis] = useState("Undefined");
  const [relatedEvent, setRelatedEvent] = useState([]);


  const handleInfoChange = (e) => {
    setInfo(e.target.value)
  }
  const handleAnalysisChange = (e) => {
    setAnalysis(e.target.value)
  }

  const handleRelatedEvents = (e) => {
    setRelatedEvent(e.target.value)
  }

  const relatedEventsData = props.data.map(opt => ({ label: opt.info, value: opt._id }));

  const onSubmit = async () => {
    setLoading(true);
    const MySwal = withReactContent(Swal);

    const eventData = {
      UUID: uuidv4(),
      info: info,
      analysis: analysis,
      relatedEvent: relatedEvent,
    }

    axios
      .post(`${process.env.REACT_APP_PROXY}/api/events`, eventData)
      .then((res) => {
        console.log(res);
        setLoading(false);
        MySwal.fire(
          "Success!",
          "A new event has been saved successfully",
          "success"
        );
      })
      .catch((error) => {
        console.log(error);
      });
    
  };

  return (
    <div className="panel-body">
      <Form
        ref={form}
        onSubmit={handleSubmit(onSubmit)}
        className="form-horizontal"
      >
        <div className="row">
          <div className="col-lg-6">
            <div className="mb-3">
              <Form.Label>Info</Form.Label>
              <Form.Control
                type="text"
                placeholder="Enter info..."
                {...register("info", { required: true })}
                value={info}
                onChange={handleInfoChange}
              />
              {errors.info && (
                <ul className="parsley-errors-list filled" id="parsley-id-7" aria-hidden="false">
                  <li className="parsley-required">This value is required.</li>
                </ul>
              )}
            </div>
           
          </div>
          
          <div className="col-lg-6">
            <div className="mb-3">
              <Form.Label>Related events</Form.Label>
              <Select
                options={relatedEventsData}
                value={relatedEvent}
                isMulti
                onChange={handleRelatedEvents}
              />

            </div>
          </div>
         
          <div className="col-lg-12">
            <Button variant="primary" type="submit">
              {loading ? "Saving..." : "Save"}
            </Button>
          </div>
        </div>
      </Form>
    </div>
  );
}

Could you please guide me how to make it work! Thank you

CodePudding user response:

you can make use of Select onChange event handler which passes the selected options as an array as argument ..

from that you can map over it to get the values as required something as below:

  const handleChange = (opts) => {
    const selectedValues = opts.map((opt) => opt.value);
    setSelectedValues(selectedValues);
  };

Please check the working sample for better clarity

  • Related