Green
Green

Reputation: 30795

How to setAttribute on React JSX element dynamically?

I want to set key attribute on React element dynamically, like below. However both approaches do not work. I know I can use other technique for that, but I'd like to know if it is possible to do so this way:

One:

{
    new Array(3).fill(<td></td>).map((td,i) => {
        td.setAttribute('key', i);
        return td;
    })
}

Two:

{
    new Array(3).fill(document.createElement(td)).map((td,i) => {
        td.setAttribute('key', i);
        return td;
    })
}

The error

// td is {$$typeof: Symbol(react.element), type: "td", key: null, ref: null, props: {…}, …}
// Uncaught (in promise) TypeError: td.setAttribute is not a function

Upvotes: 3

Views: 13130

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074138

Both of those put the same td element in the array three times. Definitely not what you want to do. You want to create three tds. You could do that by filling with null and then mapping in the elements:

{
    Array(3).fill(null).map((_, i) => <td key={i}></td>)
}

or using Array.from's callback:

{
  Array.from(Array(3), (_, i) => <td key={i}></td>)
}

Live Example:

const Row = () =>
  <tr>
    {
      Array.from(Array(3), (_, i) => <td key={i}>TD #{i}</td>)
    }
  </tr>
;

ReactDOM.render(
  <table>
    <tbody>
      <Row />
    </tbody>
  </table>,
  document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Upvotes: 2

Related Questions