[SOLVED]-REACT MAP WITH OPENING AND CLOSING TAGS-REACTJS

REACT MAP WITH OPENING AND CLOSING TAGS-REACTJS

neither <ol> nor </ol> are valid jsx, which is why your current code fails.

my advice would be to reshape your data structure such that you are not relying on the 1 and -1 to tell you when to go up or down a level in nesting. something like this would be easier to work with:

const linkarray = ['value', 'another value', ['third value'], 'fourth value']

this way, your data structure has the same shape as the desired output.

from here, we can define a recursive function, which will render a new <li> element when it encounters a string, and a new <ol> element when it encounters an array:

const nestedlist = link => {
  if (link instanceof array) {
    return <ol>{link.map(nestedlist)}</ol>;
  } else {
    return <li>{link}</li>;
  }
}

then return the following in your main component’s render method (a call to the function we just defined wrapped in an outer set of <ol> tags):

<ol>{linkarray.map(nestedlist)}</ol>

the following html is rendered:

<ol>
  <li>value</li>
  <li>another value</li>
  <ol>
    <li>third value</li>
  </ol>
  <li>fourth value</li>
</ol>

which is the desired output (minus the <somecomponent> tags, which i left out for simplicity’s sake – they don’t affect the logic).

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments