Search code examples
htmlreactjsobjectpchart

How to place an HTML tag in an object?


I want to render a list from an array of objects in React. The 'answer' key contains the following text...

Question: blah,
Answer: `List title
         The biggest benefits of Kin are:
         1.
         2.
         3.
         4.
`

I would like to add spacing between the list items. Like I've demonstrated here...

Answer: `List title
         The biggest benefits of Kin are:
         <br/>
         1.
         <br/>
         2.
         <br/>
         3.
         <br/>
         4.

Adding any html tag between the list items doesn't work as the tag gets rendered like so:

1.<br [innerHTML]>2.<br [innerHTML]>...

Any ideas?


Solution

  • You could use the map function for iterating over the array of answer list.
    Here's how it will look:

    import React from 'react'
    export default class TestRoute extends React.Component {
        render() {
            const ANSWER_OBJECT =
            {
                title: "Answer Title 1",
                answers: [
                    "The biggest benefit of ....",
                    "1. ",
                    "2. ",
                    "3. "
                ]
            }
    
            return (
                <div>
                    <h3>{ANSWER_OBJECT.title}</h3>
                    {ANSWER_OBJECT.answers.map((item) => <div>{item}</div>)}
                </div>
            )
        }
    }
    

    RESULT:

    Answer Title 1
    The biggest benefit of ....
    1.
    2.
    3.

    If you have answer in the form of String instead of array, you could use the split method to convert it to array.

    render() {
            const answerString =
                `The biggest benefit of ....
                1. Point 1
                2. Point 2
                3. Point 3
                `
    
            return (
                <div>
                    {answerString.split("\n").map((item) => <div>{item}</div>)}
                </div>
            )
        }