Search code examples
javascriptreactjsreact-bootstrap

Dynamically create rows in react bootstrap from 1d array


I have an array of column names and am trying to dynamically create a table with 2 columns (name and type). "Name" will be the name of the column and "type" will be a dropdown button to select a type (to be implemented later, just want to print a button for now).

This the code I have so far, it doesn't work at all and I'm getting "Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag".

Cols example, I am loading it with the below code:

const [cols, setCols] = useState(null);
d3.csv('/test.csv').then(data -> setCols(data.columns));

console.log(cols);
["name", "address", "zip", "number", ...]
<ReactBootstrap.Table striped bordered hover>
  <thead>
    <tr>
      <th>Column</th>
      <th>Import As</th>
    </tr>
  </thead>
  <tbody>
    {
      cols.map((col) => (
        <td><p>{col}</p></td>
        <td><div><button>Skipped</button></div></td>
      ))
    }
  </tbody>

Fixed it, changes below:

const [cols, setCols] = useState([]);

cols.map((col) => (
    <Fragment>
        <tr>
          <td><p>{col}</p></td>
          <td><div><button>Skipped</button></div></td>
        </tr>
    </Fragment>
))

Solution

  • Try wrapping the contents of your returned HTML with a Fragment tag:

    cols.map((col) => (
        <Fragment>
            <td><p>{col}</p></td>
            <td><div><button>Skipped</button></div></td>
        </Fragment>
    ))