Search code examples
javascriptcssreactjshtml-tableredraw

Border redraw mismatch in React tables


I'm brand new to React and CSS, and so I decided to make a calculator web app. Everything works as intended except the borders. Sometimes when I check or uncheck operations, the borders between rows won't line up across columns. They can then fix themselves after more clicks. More strangely, I haven't run into this issue when testing it in Firefox. I'm using border-collapse in the CSS file. I've included the core of the table code and style below. Thanks for any help!

index.css

#output {
  font-size: 1.5em;
}

#result {
  border:4px solid #000;
  border-collapse: collapse;
}

#result td {
  border:1px solid #000;
}

#result th {
  border:1px solid #000;
  border-bottom:2px solid #000;
  padding: 10px;
}

#result tr td {
  padding: 4px;
  padding-left: 10px;
  width: 0;
  white-space: nowrap;
}

index.js

function Output(props) {
  const tableData = [];
  const n1 = parseInt(props.num1);
  const n2 = parseInt(props.num2);
  if (props.doAdd)  tableData.push({key: 'addRow', op: 'Addition',       num: add(n1, n2)});
  if (props.doSub)  tableData.push({key: 'subRow', op: 'Subtraction',    num: subtract(n1, n2)});
  if (props.doMul)  tableData.push({key: 'mulRow', op: 'Multiplication', num: multiply(n1, n2)});
  if (props.doDiv)  tableData.push({key: 'divRow', op: 'Division',       num: divide(n1, n2)});

  return (
    <div id='output'>
      <ResultTable data={tableData} />
    </div>
  );
}

function ResultTable(props) {
  let rows = props.data.map(row => {
    return <ResultRow key={row.key} op={row.op} num={row.num} />
  });

  return (
    <table id='result'>
      <thead>{<ResultHead />}</thead>
      <tbody>{rows}</tbody>
    </table>
  );
}

function ResultHead() {
  return (
    <tr>
      <th>Operation</th>
      <th>Result</th>
    </tr>
  );
}

function ResultRow(props) {
  return (
    <tr>
      <td>{props.op}</td>
      <td>{props.num}</td>
    </tr>
  );
}

Solution

  • This will work

    Remove border-collapse: collapse; and add border-spacing: 0; instead.

    #result {
          border:4px solid #000;
          border-spacing: 0;
        }
    

    Working example on stackblitz: https://stackblitz.com/edit/react-aqyy9r