A
A
Anya Kolomenskaya2020-09-06 22:22:44
JavaScript
Anya Kolomenskaya, 2020-09-06 22:22:44

Why isn't the set of React components rendered?

Why isn't the set of React components rendered? - I can't catch the error. The following thing doesn't output anything, even though it should:

return document.getElementsByTagName("main")[0].getElementsByTagName("section").map(theArrayElement => <p>Paragraph!</p>);

However, if you check the first part of the expression (where the array of elements is formed):
return document.getElementsByTagName("main")[0].getElementsByTagName("section").length;

... then "2" is displayed quite correctly - there should be so many of them - so that the array is formed. If you check the contents of this array:
return document.getElementsByTagName("main")[0].getElementsByTagName("section")[0].innerText;

...then "Test text!" - this is exactly the text that I stuffed inside the test section - so the array contains the correct elements. Now I check the second part (which uses the simplest map() ):
return [0, 0, 0].map(theArrayElement => <p>Paragraph!</p>);

...which also works correctly, outputting three paragraphs with the text "Paragraph!". So, the first half of the expression works for me and the second half of the expression works, but the whole expression does not work. I don't understand what else could be the issue.
PS : The complete class is very simple and looks like this:
class ContentsList extends React.Component {
    render() {
        // Тот самый return - и больше ничего
    }
}

PPS : I know that theArrayElement => <p>Paragraph!</p> is stupid, since the theArrayElement variable is not used in the function itself. But the normal logic will be later, and there the variable will already be used. While it is necessary to understand at least this basic problem.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FabiBoom, 2020-09-06
@FabiBoom

I don't know what you are trying to do and I understand that the reason is that the getElementsByTagName method returns not an array, but an HTMLCollection , which does not have the map method you are trying to use.
You can solve the problem by casting the result to an array:

Array.from(document.getElementsByTagName("main")[0].getElementsByTagName("section")).map(theArrayElement => <p>Paragraph!</p>);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question