Home > Blockchain >  react ternary operator problem, solvable only with jquery?
react ternary operator problem, solvable only with jquery?

Time:10-19

I'm new to React and try to make a simple crud with Springboot. at certain point I need to use a ternary operator, but it doesn't work. I used it before in React with no problem, I don't understand why now is not working. So I used a function and is working, except when I have to empty a div, which gave me a problem and need to use jquery. So now the code is working, I just would like to know what I'm doing wrong in the ternary and in emptying the div with javascript. I will post the full working code, then just the piece of code that would like to use vs the code that is actually working. Thanks for your patience

import { React, useState, useEffect } from "react";
import { useHistory } from "react-router";
import ServiceUtente from "../service/ServiceUtente";
import $ from "jquery";

const Utente = () => {
  const history = useHistory();
  const [utenti, setUtenti] = useState([]);
  const [isDeleted, setIsDeleted] = useState(false); 
  const [searchBy, setSearchBy] = useState("");
  let checkedNome = false;
  let checkedEmail = false;
  let checkedProfilo = false;

  useEffect(() => {
    retrieveUtenti();
  }, [isDeleted]);

  // retrieve data from db and store it into utenti
  const retrieveUtenti = () => {
    ServiceUtente.utenteGetAll()
      .then((response) => {
        setUtenti(response.data);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const viewUtente = (id) => {
    history.push(`/view-utente/${id}`);
  };

  const aggiungiUtente = () => {
    history.push("/aggiungi-update-utente/_add");
  };

  const deleteUtente = (id) => {
    ServiceUtente.utenteDelete(id)
      .then((response) => {
        setIsDeleted(!isDeleted);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const updateUtente = (id) => {
    history.push(`/aggiungi-update-utente/${id}`);
  };

  const handleSearch = (e) => {
    setSearchBy(e.target.value);
  };

  const handleNome = (e) => {
    checkedNome = e.target.checked;
    console.log("nome: "   checkedNome);
    nomeForm();
  };
  const handleEmail = (e) => {
    checkedEmail = e.target.checked;
    console.log("email: "   checkedEmail);
  };
  const handleProfilo = (e) => {
    checkedProfilo = e.target.checked;
    console.log("profilo: "   checkedProfilo);
  };

  const formSearchBy = () => {
    // console.log("");
  };

  const nomeForm = () => {
    if (checkedNome === true) {
      document.getElementById("nomeForm").innerHTML = `
        <input
          type="text"
          className="form-control"
          placeholder="Search Utente"
          value="${searchBy}"
          onChange="${handleSearch}"
        />`;
    } else {
      // document.getElementById("nomeForm").innerHTML = "";
      $("#nomeForm").empty();
    }
  };

  return (
    <div className="row">
      <div className="col-sm-10 offset-1">
        <h2 className="login-title my-4" style={{ textAlign: "center" }}>
          GM Utente
        </h2>

        {/* ***********************SEARCH BAR****************************************** */}
        <form onClick={formSearchBy}>
          <h4 style={{ textAlign: "center" }}>
            Spuntare i campi desiderati per la ricerca
          </h4>
          <div className="form-check">
            <input
              onChange={handleNome}
              className="form-check-input"
              type="checkbox"
              name="nomeCheck"
              value=""
              id="nomeUtente"
            />
            <label className="form-check-label" htmlFor="nomeUtente">
              Nome Utente
            </label>
            <div id="nomeForm">{nomeForm()}</div>
          </div>
          <div
            className="input-group-append my-2 text-center"
            style={{ textAlign: "center" }}
          >
            <button
              className="btn btn-success"
              type="submit"
              id="button-addon2"
            >
              Search
            </button>
          </div>
        </form>
        {/* ***********************END SEARCH BAR*********************************** */}

        <button
          type="button"
          className="btn btn-primary my-2"
          onClick={() => aggiungiUtente()}
        >
          Aggiungi Utente
        </button>
        <table
          className="table table-striped table-bordered"
          style={{ textAlign: "center" }}
        >
          <thead>
            <tr>
              <th>Id Utente</th>
              <th>Nome Utente</th>
              <th>Email</th>
              <th>Password</th>
              <th>Profilo Utente</th>
              <th>Azioni</th>
            </tr>
          </thead>

          <tbody>
            {utenti.map((utente) => (
              <tr key={utente.idUtente}>
                <td>{utente.idUtente}</td>
                <td>{utente.nomeUtente}</td>
                <td>{utente.email}</td>
                <td>{utente.password}</td>
                <td>{utente.profiloUtente.nomeProfilo}</td>
                <td>
                  <button
                    onClick={() => viewUtente(utente.idUtente)}
                    type="button"
                    className="btn btn-secondary mx-1"
                  >
                    Details
                  </button>
                  <button
                    onClick={() => updateUtente(utente.idUtente)}
                    type="button"
                    className="btn btn-warning mx-1"
                  >
                    Update
                  </button>
                  <button
                    onClick={() => deleteUtente(utente.idUtente)}
                    type="button"
                    className="btn btn-danger mx-1"
                  >
                    Delete
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default Utente;

All this code is working but I would like to use this

{checkedNome === true ? (
              <input
                type="text"
                className="form-control"
                placeholder="Search Utente"
                value={searchBy}
                onChange={handleSearch}
              />
            ) : null}

Instead of this function

const nomeForm = () => {
    if (checkedNome === true) {
      document.getElementById("nomeForm").innerHTML = `
        <input
          type="text"
          className="form-control"
          placeholder="Search Utente"
          value="${searchBy}"
          onChange="${handleSearch}"
        />`;
    } else {
      // document.getElementById("nomeForm").innerHTML = "";
      $("#nomeForm").empty();
    }
  };

Also, in this function, why the Jquery syntax is working and the '.innerHTML = "";' commented out is not? Thanks

CodePudding user response:

Issue

The issue is that you aren't updating any state in order to trigger a render. checkedNome is declared in the function body and mutating it won't trigger React to do anything.

let checkedNome = false;

const handleNome = (e) => {
  checkedNome = e.target.checked; // <-- mutation
  console.log("nome: "   checkedNome);
  nomeForm(); // <-- DOM mutation
};

Solution

Move the checkedNome into component state:

const [checkedNome, setCheckedNome] = React.useState(false);

Update handleNome to enqueue a state update:

const handleNome = (e) => {
  const { checked } = e.target;
  setCheckedNome(checked);
};

Update the render return to conditionally render the input:

<div id="nomeForm">
  {checkedNome && (
    <input
      type="text"
      className="form-control"
      placeholder="Search Utente"
      value={searchBy}
      onChange={handleSearch}
    />
  )}
</div>
  • Related