React.js "Invariant violation: findComponentRoot"

I know that the error is related to the attached files and the _.map attached function, but I cannot figure out how to do this.

Below are the parts of the rendering function:

What I want to do:

  • Check this.props.currencylist exists
  • Then display the <select> dropdown
  • with <options> coming from this.props.currencylist

 { this.props.currencylist ? <select id="fiatselector" onChange={this.onSelectCurrency} value {this.props.selectedcurrency}> { _.map(this.props.currencylist, function(currency) { return <option value={currency}> {currency} </option> }) } </select> : "" } 

Thank you very much!

Btw, it works fine during the first rendering, it is mistaken when it needs to be updated, reindexing with a new list of currencies causes an error

+6
source share
2 answers

The actual problem here is the space around the meaning.

 <option> {x} </option> 

It should be:

 <option>{x}</option> 

The first finishes rendering:

 <option><span> </span>{x}<span> </span></option> 

The browser removes the range wrappers, but React is still expecting them there.

+15
source

I was able to reproduce your error. Apparently you need to add the key attribute to your parameter tags. I would like to give a better explanation, but I don't know enough about ReactJs to explain.

Here is the corresponding change based on your snippet (only the change here adds the key attribute. I just used the currency as the key here):

 _.map(this.props.currencylist, function(currency) { return <option key={currency} value={currency}> {currency} </option> }) 

Here is a simple example that I used for testing (slightly modified rendering, but the same idea):

 var CurrentSelector = React.createClass({ render: function() { var options = this.props.currencylist.map(function(currency) { return <option key={currency} value={currency}> {currency} </option> }); if (this.props.currencylist) { return <div><select id="fiatselector">{options}</select></div> } else { return <div></div> } } }); var App = React.createClass({ getInitialState: function() { return { currencylist: [1,2,3], selectedcurrency: 1, } }, render: function() { return ( <div> <CurrentSelector currencylist={this.state.currencylist} selectedcurrency={this.state.selectedcurrency} /> <button onClick={this.handleClick}>test</button> </div> ); }, handleClick: function() { this.setState({ currencylist: [2, 3, 4, 5], selectedcurrency: 2, }) } }); 
+1
source

Source: https://habr.com/ru/post/980516/


All Articles