Loop function inside html in javascript (React)

I want to loop over my function SliderComponent, with different inputs, inside the Html in order to create several components.
I found this solution online where we build string and return as Html, using “id” and “getElementById” but I can’t make it work.

 export function GrommetButtonEx() {
      return (
          <Grommet theme={grommetTheme}>
              border={{ color: "grey", size: "medium" }}
              background={{ color: "black", opacity: "strong" }}
              style={{ borderRadius: "15px" }}
              <Accordion style={{ color: "grey" }}>
                  style={{ height: "30px" }}
                    <Text color="white" weight="bold" size="small">
                      Joint Position
                  <div id="output_div"></div>
                  {/* This works
                    sliderName={"slider 5"}
    window.onload = function () {
      var outputHTML = "";
      for (var k = 0; k < 5; k++) {
        outputHTML +=
          '<SliderComponent sliderName={"slider ' +
          k +
          '"} min={0} max={17} step={0.1}';
      document.getElementById("output_div").innerHTML = outputHTML;

I got the following error for:

TypeError: Cannot set properties of null (setting 'innerHTML')


document.getElementById(“output_div”).innerHTML = outputHTML;

Is this the right way to do it, or is there a better way?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

In react you can write Javascript inside the “HTML” (This is called JSX). You don’t have to write any Javascript logic outside the function component.

Also, you don’t have to use innerHTML, instead, you have to write in JSX (inside the HTML), and make it return an instance of the component for each time the loop runs.

And to replace the "onload" you can use a hook called componentDidMount.

As for the question of how to write the loop logic in JSX (inside the HTML), here is a link to a similar question.

Method 2

You should use the componentDidMount hook instead of onload.

componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here (like in your case).

Read more about componentDidMount here – https://reactjs.org/docs/react-component.html#componentdidmount

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x