Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js this.props.data.map() is not a function

I'm messing around with react and trying to parse and render a json object. Right now, I'm just setting it with a hard-coded object for testing and not getting it from an ajax call.

<script type="text/jsx">

var Person = React.createClass({
render: function() {
  return (
    <div>
      <p className="personName"></p>
      <p className="personSA1"></p>
      <p className="personSA2"></p>
      <p className="zip"></p>
      <p className="state"></p>
      <p className="country"></p>
    </div>
  );
 }
});

var PersonDiv = React.createClass({
render: function() {
  var personNodes = this.props.data.map(function(personData){
    return (
      <Person
        personName={personData.person.firstname}
        personSA1={personData.person.street1}
        personSA2={personData.person.street2}
        zip={personData.person.zip}
        state={personData.person.state}
        country={personData.person.country}>
      </Person>
    )
});
return (
  <div>
    {personNodes}
  </div>
);
}
});

React.render(
 <PersonDiv data={data} />,
document.getElementById('jsonData')
);

I'm setting the data variable with

<script>
  var data = "[" + '<%=data%>' + "]";
</script>

The data object is one that I'm creating on the java side of a portlet. I know that the json is valid, because I can use JSON.parse(json) to parse and traverse the string, but I keep getting that map() is not a function.

like image 461
jordaniac89 Avatar asked Feb 19 '26 07:02

jordaniac89


1 Answers

It appears that your data is not a json object, it is a string. You probably need to run data = JSON.parse(data); to convert your data into an actual javascript object to be able to use it. An easy test for this would be to run

<script>
  var data = "[" + '<%=data%>' + "]";
  console.log(data);
  console.log(JSON.parse(data));
</script>

You should notice the difference.

like image 158
Butters Avatar answered Feb 21 '26 22:02

Butters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!