Ad

ReactJs - Combine Arrays And Show

- 1 answer

I have two array one of values, and the other of descriptions.

I would like to create a description list <dl>, the <dd> containing the description and the <dl> containing the value.

Can anyone please tell me how I can alternate each array to create the following list and render in react?

<dl>
  <dt>value</dt>
  <dd>description</dd>
  <dt>value</dt>
  <dd>description</dd>
</dl>
Ad

Answer

You can use simple for loop:

render() {
    var descriptions = [...];
    var values = [...];

    var elems = []; // array of elements to be rendered
    // assume `descriptions` and `values` has the same length
    for (var i = 0; i < descriptions.length; i++) {
        elems.push(<dt>{values[i]}<dt>);
        elems.push(<dd>{descriptions[i]}<dd>);
    }

    return (<dl>{elems}</dl>); // render elements
}
Ad
source: stackoverflow.com
Ad