skip to Main Content

I have a form with a text input and three selects, this form is used to perform a CRUD, I have the option to edit when this option is pressed, the form inputs are filled with the information of the record that was selected, I achieve that the text type input to populate correctly but I have not been able to get the select inputs to be set with the option of the selected record. What can I do to achieve this.
enter image description here

This is my code:

import React, { useEffect, useState } from "react";

const initialFormTeam = {
  equipos_id: null,
  nombre: "",
  entrenador: null,
  estatus: null,
  competencia: null,
  grupo: null,
};

function RegisterFormTeam(props) {
  const {
    createTeam,
    dataTrainer,
    dataStatus,
    dataCompetition,
    dataToEdit,
    setDataToEdit,
    updateTeam,
  } = props;

  //States
  const [form, setForm] = useState(initialFormTeam);
  const [message, setMessage] = useState();
  const [response, setResponse] = useState(null);
  const [selectValues, setSelectValues] = useState({
    trainer: "",
    status: "",
    competition: "",
  });

  useEffect(() => {
    if (dataToEdit) {
      setForm(dataToEdit);
    } else {
      setForm(initialFormTeam);
    }
  }, [dataToEdit]);

  const handleChange = (e) => {
    setForm({
      ...form,
      [e.target.name]: e.target.value,
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (form.equipos_id === null) {
      createTeam(form);
      setMessage("Team added successfully");
      setResponse(true);
      setTimeout(() => {
        setResponse(false);
      }, 3000);
    } else if (form.equipos_id !== null) {
      updateTeam(form, {
        nombre: form.nombre,
        entrenador: form.entrenador,
        estatus: form.estatus,
        competencia: form.competencia,
      });
    }
    setSelectValues({
      trainer: "",
      status: "",
      competition: "",
    });
    handleReset();
  };

  const handleSelect = (e) => {
    const fieldName = e.target.name;
    const fieldValue = e.target.value;

    if (fieldName === "entrenador") {
      setForm({
        ...form,
        entrenador: fieldValue,
      });
      setSelectValues({
        ...selectValues,
        trainer: fieldValue,
      });
    } else if (fieldName === "estatus") {
      setForm({
        ...form,
        estatus: fieldValue,
      });
      setSelectValues({
        ...selectValues,
        status: fieldValue,
      });
    } else if (fieldName === "competition") {
      setForm({
        ...form,
        competencia: fieldValue,
      });
      setSelectValues({
        ...selectValues,
        competition: fieldValue,
      });
    }
  };

  const handleReset = (e) => {
    setForm(initialFormTeam);
    setDataToEdit(null);
  };

  return (
    <div>
      <h1>Register your teams</h1>
      <form onSubmit={handleSubmit}>
        <h3>{dataToEdit ? "Edit" : "Add"}</h3>
        <label htmlFor="nombre">Name of the team </label>
        <input
          type="text"
          id="nombre"
          name="nombre"
          onChange={handleChange}
          value={form.nombre}
          placeholder="Write the name of the team"
        />
        <br />
        <br />
        <label htmlFor="trainer">Trainer </label>
        <select
          id="trainer"
          name="entrenador"
          onChange={handleSelect}
          value={selectValues.trainer}
        >
          <option value="" hidden>
            Select the trainer
          </option>
          {dataTrainer.length > 0 ? (
            dataTrainer[0].users.map((el, index) => (
              <option key={index} value={el.user_id}>
                {`${el.nombres} ${el.apellidos}`}
              </option>
            ))
          ) : (
            <option value="" disabled>
              Loading...
            </option>
          )}
        </select>
        <br />
        <br />
        <label htmlFor="status">Status </label>
        <select
          id="statusTeam"
          name="estatus"
          onChange={handleSelect}
          value={selectValues.status}
        >
          <option value="" hidden>
            Select status team
          </option>
          {dataStatus.length > 0 ? (
            dataStatus.map((el, index) => (
              <option key={index} value={el.catalogo_id}>
                {el.clave}
              </option>
            ))
          ) : (
            <option value="" disabled>
              Loading...
            </option>
          )}
        </select>
        <br />
        <br />
        <label htmlFor="competition">Competition </label>
        <select
          id="competitionTeam"
          name="competition"
          onChange={handleSelect}
          value={selectValues.competition}
        >
          <option value="" hidden>
            Select competition
          </option>
          {dataCompetition.length > 0 ? (
            dataCompetition.map((el, index) => (
              <option key={index} value={el.competicion_id}>
                {el.nombre}
              </option>
            ))
          ) : (
            <option value="" disabled>
              Loading...
            </option>
          )}
        </select>
        <br />
        <br />
        <input type="submit" value={dataToEdit ? "Edit" : "Add team"} />
        <input type="reset" value="Clear" onClick={handleReset}></input>
      </form>
      {response && <p>{message}</p>}
    </div>
  );
}

export default RegisterFormTeam;
const TableRowTeam = ({ el, deleteTeam, setDataToEdit, }) => {

  return (
    <tr>
      <td>{el.nombre}</td>
      <td>{`${el.users.nombres} ${el.users.apellidos}`}</td>
      <td>{el.catalogos.clave}</td>
      <td>{el.competicion.nombre}</td>
      <td>
        <button onClick={() => setDataToEdit(el)}>Edit</button>
        <button onClick={() => deleteTeam(el.equipos_id, el.nombre)}>
          Delete
        </button>
      </td>
    </tr>
  );
};
export default TableRowTeam;

2

Answers


  1. Chosen as BEST ANSWER

    The solution that I applied to solve my problem was the following: Because the selected attribute is not used in React, you must use the value attribute at the root of the select tag. So using the value attribute we check if the selected element is the currently selected option if form.competition is different from null we set the selected value in the select otherwise we leave the tag empty.

            <label htmlFor="trainer">Trainer </label>
            <select
              id="trainer"
              name="entrenador"
              onChange={handleSelect}
              {...(form.entrenador !== null
                ? { value: form.entrenador }
                : { value: selectValues.trainer })}
            >
              <option value="" hidden>
                Select the trainer
              </option>
              {dataTrainer.length > 0 ? (
                dataTrainer[0].users.map((el, index) => (
                  <option key={index} value={el.user_id}>
                    {`${el.nombres} ${el.apellidos}`}
                  </option>
                ))
              ) : (
                <option value="" disabled>
                  Loading...
                </option>
              )}
            </select>


  2. You need to add the selected attribute (selected="selected") to the <option> element if it is the currently selected option. For example, if the trainer’s user id (el.user_id) is the same as the currently selected trainer (form.entrentador), then you would add the selected attribute.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search