react-dropdown-tree-select issues with setState and index

Viewed 935

I'm using react dropdown tree select within a component.

class PriceComponent extends Component {
    constructor(props) {
        this.state = {
          index: 0,
          rate: [{
             price: 0,
             regions: []
          }]
        }
    }

    //add more event
    addMore = () => {
       this.setState({ rate: this.state.rate.concat([{ price: 0, regions: [] }]) })
    }

    //dropdown tree select
    onChange = (currentNode, selectedNodes) => {
       const arr_values = selectedNodes.map(v => v.value);
    }

   //price change
   handleChange = (e) => {
       this.setState({
         [e.target.name]: e.target.value
       })
   }

    render() {
        //many fields
        {this.state.rate.map((r, idx) => (
            <div key={idx}>
               <input type="text" name="price" onChange={(e) => this.handleChange(e, i)} />
               <DropdownTreeSelect data={regions} onChange={this.onChange} />
            </div>
        )}
        <button onClick={this.addMore.bind(this)}>Add More</button>
    }
}

The above is my code but I am facing some issues and I'm not sure how to proceed with it.

  1. In the dropdown component's onChange, if I do the setState, it keeps re-rendering, so tried I the 'prevent re-render on parent' but I get an error saying the data is undefined (I had replaced the componentWillReceiveProps with getDerivedStateFromProps)
  2. When a new set of fields(price + regions) is added, the value in the previous regions dropdown refreshes. Can this be prevented?
  3. Is there a way to get the index of the dropdown ? I tried passing the index with the onChange but it didn't work.

Any help is appreciated. Thanks in advance.

1 Answers

In your regions variable needs to be a state variable. And on any state changes that causes a re-rendering, regions needs to reflect what you have chosen/unchosen in the DropdownTreeSelect dropdown list.

I solved my problem by adjusting onChange method to modify regions state variable so when DropdownTreeSelect re-renders, your regions needs to have its children checked or un-checked.

Related