1

I would like to generate a table in render() method of my class.

So in different example/project in past, I have pushed divs to an array and then return this array and it worked fine in terms of displaying but in this case when I call this.tableGenerator() it displays the result as a plain text, not rendered HTML.

Can you please tell me why this happens? Or maybe there is another method I can loop this table out?

tableGenerator = () => {

    let table = [];

    table.push('<tr>');
    //loop for columns

    table.push('</tr>');

    return table;

}

Here is example I was talking about: it generates a board of divs and now I want to change it to display as a table:

createMap = (cols, total) => {
    let table = []; let nL = ''; let idRow = 0; let idCol = 0;

    for (let i = 0; i < total; i++) {
      idCol++;
      if (i%cols === 0){
        nL = 'newLine';
        idRow += 1;
        idCol = 1;
      }
      else {
        nL = '';
      }

      let toggledBackground = '';

        switch (this.state.cellStates[i]) {
          case 1:
            toggledBackground = 'alive';
            break;

          case 2:
            toggledBackground = 'dead';
            break;

          default:
            toggledBackground = '';
        }

      table.push(<div id={"pos-"+idRow+"-"+idCol} className={"square "+nL+" "+toggledBackground} onClick={() => this.changeState(i)}></div>);
    }
    return table;
  }

1 Answer 1

4

You need something like this:

tableGenerator = () => {
  return (
    <table>
      <tr>
        {columns.map(column => <th>{column.data}</th>)}
      </tr>
    </table>
  );
}

Where column.data is the info you want to display (I used data as a general value but it could be label, name, info, etc).

Sign up to request clarification or add additional context in comments.

3 Comments

Okay, but then why the example above works like a charm (divs)? //i have updateted original post
Because in your new example you are pushing strings with tags, in your old example you are pushing proper divs with JSX. Note the apostrophes in the new one.
See: JSX and how it works reactjs.org/docs/introducing-jsx.html Plain tags in JSX is just syntactic sugar for React.createElement. If you write apostrophes around them you are just loading strings, not calling the important createElement function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.