Home > Back-end >  how to access this json data in react return
how to access this json data in react return

Time:07-11

How i can able access this

{
    "user": {
        "questionsz": [
            {
                "_id": "62737b55583793fad608aaa2",
                "question": "<b>Directions(Q.1 to Q.5 ): </b><p>What approximate value should come in place of question mark (?) in the following questions?  ",
                "__v": 0
            }
        ]
        }
    }

Here Below my code

const index = (user) => {
    return (
      <div>
            question.  {user.question}
      </div>  
    )
  }

how can i access question property from above json to return actual data to show in frontend

CodePudding user response:

Your question is not very much clear but if you are accepting the JSON file as a props to your functional component you could Destructure the json data like


const index = ({ user }) => {
    return (
      <div>
            question.  {user.question}
      </div>  
    )
  }


Now the user props contains the

{
  "questionsz": [
    {
      "_id": "62737b55583793fad608aaa2",
      "question": "<b>Directions(Q.1 to Q.5 ): </b><p>What approximate value should come in place of question mark (?) in the following questions?  ",
      "__v": 0
    }
  ]
}

which you can access the questions like user.question

But my suggestion is to show the data in list format like

const index = ({ user }) => {
    return (
      <div>
            show user.question in table and question.question is html string
            <ul>
                {user.questionsz.map(question => (
                    <li key={question._id} dangerouslySetInnerHTML={{ __html:  question.question }} />
                ))}
            </ul>
      </div>  
    )
  }

i added dangerouslySetInnerHTML because i see the question is html strings. refer here for more info about rendering html string Render HTML string as real HTML in a React component

CodePudding user response:

Use dangerouslySetInnerHTML attribute. More info here- https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

  • Related