Eugene Podoliako Eugene Podoliako - 2 months ago 18
React JSX Question

React ReferenceError:unknown node of type "JSXSpreadChild" with constructor "Node"

I cannot undestand what is the problem in following componens, and why it lead to error (the error appeared when I try to make js file through webpack). This issues appeared when

{...this.state.options}
was added in code

Component

import React from 'react';

var BoxCountComponent = React.createClass({

getInitialState: function () {
return {
options:[]
}
},
componentDidMount: function () {
for (let i=0; i<10; i++){
this.state.options.push(
<option key={i} value={i+1}>{i+1}</option>
)
}
this.forceUpdate()
},
render: function () {
return (
<select className="form-control" name="boxCount" id="boxCount">{...this.state.options}</select>
)
}
})


Error

ERROR in ./Dev/carwash/AddCarWashForm.jsx
Module build failed: ReferenceError: F:/java/projects/PitStop/Front-Dev/Dev/carwash/AddCarWashForm.jsx: unknown node of type "JSXSpreadChild" with constructor "Node"
at Generator.print (F:\java\projects\PitStop\Front-Dev\node_modules\babel-generator\lib\printer.js:356:13)
at Generator.printJoin (F:\java\projects\PitStop\Front-Dev\node_modules\babel-generator\lib\printer.js:443:12)
at Generator.printList (F:\java\projects\PitStop\Front-Dev\node_modules\babel-generator\lib\printer.js:507:17)

Answer

You have two issues:

1) You're pushing (mutating) your state object. Instead use this.setState which will automatically re-render your component. That's basically the whole idea behind React. Initialize some state, then change it with setState.

componentDidMount: function () {
    let options = []
    for (let i=0; i<10; i++){
        options.push(
            <option key={i} value={i+1}>{i+1}</option>
        )
    }
    this.setState({ options })
},

2) You don't need to spread arrays inside { } in JSX. It will handle that for you. This should be fine:

render() {
  <select className="form-control" name="boxCount" id="boxCount">
    {this.state.options}
  </select>
}
Comments