Pet
Pet

Reputation: 35

Hide/show rows in the table using Conditional rendering- React

In React I want to hide rows in the table using a value of the vehicle in a conditional rendering. The below code to hide/show row works only when used on a group of elements label and input, or with a select drop-down menu, but doesn't work on table rows.

return (
  <Fragment>
    <h2>Vehicle Details: {vehicle.vehicleId}</h2>

    <table >
      <tbody>

        {vehicle.type = "car" && (
          <Fragment>
            <tr>
              <th>Car</th>
              <td>{vehicle.reg}</td>
            </tr>
          </Fragment>
        )}

        {vehicle.type = "truck" && (
          <Fragment>
            <tr>
              <th>Truck</th>
              <td>{vehicle.reg}</td>
            </tr>
          </Fragment>
        )}

        <tr>
          <th>Bus</th>
          <td>{vehicle.reg}</td>
        </tr>

      </tbody>
    </table>
  </Fragment>
);

Upvotes: 1

Views: 1177

Answers (1)

Mushroomator
Mushroomator

Reputation: 9168

You need to use the strict comparison operator ===, not the assignment operator =.

const Table = () => {
  const [vehicle, setVehicle] = React.useState({ id: "xy", type: "car", reg: "A - 343 - 34"})
  return (
    <React.Fragment>
      <h2>Vehicle Details: {vehicle.vehicleId}</h2>
      <table>
        <tbody>
          {
            (vehicle.type === "car" && (
              <tr>
                <th>Car</th>
                <td>{vehicle.reg}</td>
              </tr>
            ))
          }
          {
            (vehicle.type === "truck" && (
              <tr>
                <th>Truck</th>
                <td>{vehicle.type}</td>
              </tr>
            ))
          }
          <tr>
            <th>Bus</th>
            <td>{vehicle.bus}</td>
          </tr>
        </tbody>
      </table>
    </React.Fragment>
  );
};

ReactDOM.render(<Table/>, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Upvotes: 2

Related Questions