Skip to content
Advertisement

Build a string and use it as an html object: Uncaught Error: Objects are not valid as a React child

I’m trying to build a React app. I have a dropdown menu component where each item is a combination of an array. Here is my code:

class PlotCardMenu extends React.Component {
  renderMenuItems(m) {
    let indices = Array(m)
      .fill(0)
      .map((v, i) => i);
    let it = new Combination(indices, 3);
    let menuItems = [];
    for (let i = 0; i < it.length; i++) {
      let item = "[" + it
        .nth(i)
        .map((e) => "f<sub>" + e + "</sub>")
        .join(",") + "]";
      console.log(item); // for sanity check
      menuItems.push(<CDropdownItem key={i}>{item}</CDropdownItem>);
    }
    return menuItems;
  }

  render() {
    return <CDropdownMenu>{this.renderMenuItems(4)}</CDropdownMenu>;
  }
}

Now if I look at the component, I’m not getting the html rendered. What I want each item to look like this: [f_0, f_1, f_2], where f_0 means f-subscript-0 etc.

Output

So I did some googling and found that I need to convert the string into html object. So I tried like this:

renderMenuItems(m) {
    let indices = Array(m)
      .fill(0)
      .map((v, i) => i);
    let it = new Combination(indices, 3);
    let menuItems = [];
    let parser = new DOMParser();
    for (let i = 0; i < it.length; i++) {
      let item = "[" + it
        .nth(i)
        .map((e) => "f<sub>" + e + "</sub>")
        .join(",") + "]";
      console.log(item);
      let doc = parser.parseFromString(item, "text/html");
      menuItems.push(<CDropdownItem key={i}>{doc}</CDropdownItem>);
    }
    return menuItems;
  }

and I’m getting this error:

Uncaught Error: Objects are not valid as a React child (found: [object HTMLDocument]). If you meant to render a collection of children, use an array instead.

How do I solve it?

Note: CDropdownItem and CDropdownMenu are from coreui-react and Combination is from js-combinatorics.

Advertisement

Answer

Actually you are sending an array of string that’s why it render array as a string so don’t try to convert string to HTML Object. You have to send Array in place of string:

class PlotCardMenu extends React.Component {
renderMenuItems(m) {
    let indices = Array(m)
        .fill(0)
        .map((v, i) => i);
    let it = new Combination(indices, 3);
    let menuItems = [];
    for (let i = 0; i < it.length; i++) {
        let item = it
            .nth(i)
            .map((e) => (<span>f<sub>{e}</sub></span>))
        console.log(item); // for sanity check
        menuItems.push(<CDropdownItem key={i}>{item}</CDropdownItem>);
    }
    return menuItems;
}

render() {
    return <CDropdownMenu>{this.renderMenuItems(4)}</CDropdownMenu>;
}
 }

I think it will resolve your problem.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement