0

I have the following function which adds JSX to the variable markup. But, when the function is called, the markup is rendered as plain text rather than JSX. How do I get the string to render as JSX instead of plain text?

Function Call:

<FormGroup controlId="items">
    {this.renderItems()}
</FormGroup>

renderItems():

renderItems() {
    let content = this.state.content;
    console.log(content);
    let markup = "<ul>";
    for (const [key, value] of Object.entries(content)) {
        if (value) {
            markup += "<li><Checkbox checked>" + key + "</Checkbox></li>"
        }
        else {
            markup += "<li><Checkbox>" + key + "</Checkbox></li>"
        }
    }
    markup += "</ul>";

    return (markup);
}
Blake Morgan
  • 767
  • 1
  • 7
  • 25

3 Answers3

4

The problem is you're not creating JSX elements. You're just creating strings. One way of accomplishing this would be

renderItems() {
  let content = this.state.content;
  return (
    <ul>
      {Object.entries(content).map(([key, value]) => (
        <li>
          <Checkbox checked={!!value}>{key}</Checkbox>
        </li>
      ))}
    </ul>
  );
}

Here, we use JSX Expressions to add dynamic values.

maazadeeb
  • 5,922
  • 2
  • 27
  • 40
0

your markup is string not JSX

Try this

 renderItems() {
    let content = this.state.content;
    let markup=[]
    console.log(content);
    markup.push(<ul>);
    for (const [key, value] of Object.entries(content)) {
        if (value) {
            markup.push(<li><Checkbox checked={true}>{ key }</Checkbox></li>)
        }
        else {
            markup.push(<li><Checkbox checked={false}>{key}</Checkbox></li>)
        }
    }
    markup.push(</ul>);

    return (markup);
}
sMojtaba Mar
  • 359
  • 2
  • 5
  • 15
0

Try this. The issue is you are appending ul and li as a strings so they will be treated as string but not jsx.

Since content is array of objects you can utilise.map for iteration and you will get new array of li elements. return the array by enclosing ul element.

Also you should never forget to add a key when returning jsx elements in loop. The key should be unique, the recommended way is to add a key from data if you have otherwise use index as key

 renderItems() {
     const { content } = this.state;
    const items = content.map((item, index) => (
            <li key={index}><Checkbox checked={item.value ? true : false }>{item.value}</Checkbox></li>
     )
    return <ul>{items}</ul>
 }
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162