noblerare noblerare - 11 days ago 6
React JSX Question

How do we pass data into this.state - React.js?

I've created a React component in my JSX file and in the constructor I have:

this.state = {data: [[200,100],[50,60],[100,300]] };


This is completely fine. It runs nicely.

However, if I add:

this.state = {linedata: [{x:200,y:100},{x:50,y:60},{x:100,y:300}] };


I get:

d3.js:265 Uncaught TypeError: Cannot read property 'length' of undefined


I am very lost as to why this is the case. Is the data supposed to be formatted in a certain way?

Answer

In React, each component's state is a simple JavaScript object. In your first example, since you said the component renders well, it seems like your component utilizes the data property of this.state.

If you change it to this.state.linedata, this.state.data will be undefined. You should probably update your component to read from this.state.linedata instead of this.state.data.

More examples of how you wrote your render function and ways you used d3 in your code would be helpful in giving you a more precise and helpful answer.

Comments