I'm currently trying to render a kind of grid with div elements in React using a formerly very simple principle in jQuery.
using jQuery, quick and easy like this:
const $field = $('#field');
for(let row = 0; row < 5; row++) {
const $row = $('<div>').addClass('row');
for(let col = 0; col < 10; col++) {
const $col = $('div').addClass('col');
$row.append($col);
}
$field.apped($row);
}
done
in React I tried now already several approaches, without success
first of all and real basic:
const rows = [], cols = [];
for(let x = 0; x < 6; x++) {
let row = React.createElement(
"div", {className: "row"}
);
rows.push(row);
}
for(let i = 0; i < 7; i++) {
let col = React.createElement(
"div", {className: "col"}
);
cols.push(col);
}
class Grid extends React.Component {
constructor(props) {
super(props);
};
render() {
return (
<>
<h1>Some Header</h1>
<div id="board">
{rows}
{cols}
</div>
</>
)
}
}
Of course, the problem here is that the cols do not nest with the rows
Since unfortunately the innerHTML function does not exist in React - I understand the hint that there are security concerns - I first tried to nest the elements with the state using methods. Without success and frankly it seems to me a step backwards to do something so simple (even using vanilla JS) with such effort.
I'm still convinced that something like this has to be much simpler - even in React. So tried with something like this:
...
class Grid extends React.Component {
constructor(props) {
super(props);
};
render() {
return (
<>
<h1>Some Header</h1>
<div id="board">
{rows.map((el, i) => {
return <div className="row" dangerouslySetInnerHTML={{__html: cols.forEach(el => {return el}) }} />;
})}
</div>
</>
)
}
}
Unfortunately without success, only the row divs are rendered. Next attempt unfortunately not either, but closer:
...
class Grid extends React.Component {
constructor(props) {
super(props);
};
render() {
return (
<>
<h1>Some Header</h1>
<div id="board">
{rows.map((el, i) => {
return <div dangerouslySetInnerHTML={{__html: cols}} />;
})}
</div>
</>
)
}
}
Outputs:
<div id="field">
<div>
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],
[object Object]
</div>
<div> ... etc
using the "i" - index iterator from that map function to iterate thru Object.keys or Object.values with some additional logic wrapped around wont work either and now I'm running out of ideas and can't find any suitable hints at the moment.
Does anyone know the final solution to do it this way?
Thanks a lot