Home > Software engineering >  How to compare Id's and interact with them ReactJS, Axios
How to compare Id's and interact with them ReactJS, Axios

Time:07-03

I'm building a laundry system with timeslots, each button has an Id ranging from 1 to 70.

Using Axios i get all available timeslots Id's, if the Id exist in "FreeSlotsList" i want the button with the corresponding id be shown in green and bookable otherwise if the Id isnt in the FreeSlotsList show red.

How would i go about doing this?

function BookingTable(props) {

  const days = [
    "Måndag",
    "Tisdag",
    "Onsdag",
    "Torsdag",
    "Fredag",
    "Lördag",
    "Söndag",
  ];

  const timeSlot = [
    ["07:00-08:30"],
    ["08:30 - 10:00"],
    ["10:00 - 11:30"],
    ["11:30 - 13:00"],
    ["13:00 - 14:30"],
    ["14:30 - 16:00"],
    ["16:00 - 17:30"],
    ["17:30 - 19:00"],
    ["19:00 - 20:30"],
    ["20:30 - 22:00"]

  ]

  const bookSlot = () => {

    const [FreeSlotsList, setFreeSlotsList] = useState([])

    useEffect(() => {
    Axios.post('http://localhost:3001/api/get/week1/ex').then((response) => {
        setFreeSlotsList(response.data)

        // I assume i need something here
      })
    }, [])

  
  }

  const renderTableHeader = () => {
    return (
      <tr>
        {days.map((days) => (
          <th>{days}</th>
        ))}
      </tr>
    );
  };

  const renderTableData = () => { 
    let id = 1;
    return (
      <tr>
        {days.map((val, i) => (
            <td>
                 {timeSlot.map((n) => (   
              <button id={id}> {n} {id  }</button> // and something here
                 ))}
            </td>
        ))}
      </tr>
    );
  };

CodePudding user response:

You could do...

const renderTableData = () => { 
    //let id = 1; no need to have this. we could use the second parameter in map below
    return (
      <tr>
        {days.map((val, i) => (
            <td>
                 {timeSlot.map((n,id) => (  // added id which also increments every new item
              // here you could add some conditional rendering
              FreeSlotsList.includes(id) ? 
                <button id={id} className={activeButton} > {n} {id}</button> :
                <button id={id} className={disabledButton} disabled > {n} {id}</button>
                 ))}
            </td>
        ))}
      </tr>
    );
  };

You could create the css for the active and disabled button classes as you wish I would suggest you to add pointer-events : none; to the disabledButton class for making the button unclickable.

Note:

Never write the useEffect and useState inside a function. They always got to be in the component.

  • Related