user2235768
user2235768

Reputation: 323

how to parse loop for json in react js

I am new to react.

    this.state = { histories: [
                   {
                  "qas":[
                    {"question": "hi1", "answer": "hello1"},
                    {"question": "hi2", "answer": "hello2"}

                  ]
                }
              ] };
render(){
    return ( 
      <div>
          <History 
          histories={this.state.histories} />
      </div>
    );
  }

In separate component page, I would like to use react js to render question and answer by loop or map, however I tried map, it didn't recognize map. I have tried for loop, but it didn't get the child attribute from it.

   const history = ({histories}) => { 
     return(
          <div>
              {histories[0].qas[0].question}
          </div>
          <div}>
            {histories[0].qas[0].answer}
          </div>
      );
}

Upvotes: 0

Views: 1373

Answers (2)

Zero
Zero

Reputation: 356

Here is an example with map, hope it will help.

const History = ({histories}) => {
  // Quick, hacky way to set key.
  // More on keys in React https://facebook.github.io/react/docs/lists-and-keys.html#keys
  let key = 1;
  const questionsAndAnswers = histories[0].qas.map(child =>
    <div key={key++}>
      <div>{child.question}</div>
      <div>{child.answer}</div>
    </div>
  );

  return (
    <div>{questionsAndAnswers}</div>
  );
};

class Histories extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      histories: [
        {
          "qas":[
            {"question": "hi1", "answer": "hello1"},
            {"question": "hi2", "answer": "hello2"}
          ]
        }
      ]
    };
  }

  render() {
      return(
        <div>
          <History histories={this.state.histories}/>
        </div>
      )
    }
}

ReactDOM.render(
  <Histories/>,
  document.getElementById("history")
);
<div id="history"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

If you remove the “div” from the <div>{questionsAndAnswers}</div>, then you’ll get the error you encountered “A valid React element (or null)…”. If you want to render multiple elements you need to wrap them in a div. More on this https://facebook.github.io/react/docs/jsx-in-depth.html#jsx-children

Upvotes: 1

Daniel Mizerski
Daniel Mizerski

Reputation: 1131

It does not recognize this histories, because I bet they are undefined at your start.

const history = ({histories}) => {
  if (!histories || histories.length < 1) return (<div>nothing</div>);
  return histories.map(v => (<div>JSON.stringify(v)</div>))
}

Another problem could be this.state.roundshistories. It is undefined in your example.

Upvotes: 1

Related Questions