samedi 23 février 2019

React - How do I handle checkbox data correctly

While I'm learning React, I started creating a rather simple project. A journey planner for TFL (Transport For London). The app gets some parameters such as From, To, and mode (Tube, Bus, Overground) and sends an API request to TFL API.

The mode data is being put together by 3 checkboxes, tube, bus and overground. It should be send as a string with commas between each word. Something like tube,bus,overground or only bus,overground etc.

This is the way I'm handling the checkbox values:

// Handling checkboxes
    const tubeVal = e.target.elements.tube.checked === true ? "tube" : "";
    const busVal = e.target.elements.bus.checked === true ? "bus" : "";
    const overgroundVal = e.target.elements.overground.checked === true ? "overground" : "";

    let mode = "";
    if (tubeVal && !busVal && !overgroundVal) {
      mode = tubeVal;
    }
    if (!tubeVal && busVal && !overgroundVal) {
      mode = busVal;
    }
    if (!tubeVal && !busVal && overgroundVal) {
      mode = overgroundVal;
    }
    if (tubeVal && busVal && !overgroundVal) {
      mode = tubeVal + "," + busVal;
    }
    if (tubeVal && !busVal && overgroundVal) {
      mode = tubeVal + "," + overgroundVal;
    }
    if (!tubeVal && busVal && overgroundVal) {
      mode = busVal + "," + overgroundVal;
    }
    if (tubeVal && busVal && overgroundVal) {
      mode = tubeVal + "," + busVal + "," + overgroundVal;
    }

Is it the right way to handle checkbox data in React? It doesn't seem right to me.




Aucun commentaire:

Enregistrer un commentaire