John Smith
John Smith

Reputation: 6259

Dropdown Component does not change on Props change

I'm displaying a Dropdown like this:

<DropdownMultiselect options={chartVariables} />

Even though chartVariables is a State and properly get's updated, the options for the Dropdown do not change, when the chartVariables get's updated.

The source code for the dropdown you can find here: https://github.com/kfrancikowski/react-multiselect-dropdown-bootstrap/blob/master/src/index.js

Can you help me to find out why the options do not change when chartVariables changes? Do I have to fix this library or can I just "force" this DropdownMultiselect to re-render?

Upvotes: 0

Views: 158

Answers (1)

Sonam Gupta
Sonam Gupta

Reputation: 383

These two approaches mentioned can help you :-

Briefly describing as per my understanding :-

As chartVariables is in the parent component and is being passed as a prop to DropdownMultiselect which is updating its state options, hence the states in the child component do not update everytime whenever the value of the props from parent changes , they needs to be updated forcefully .

I have tried using the first approach and it is working as expected ,

static getDerivedStateFromProps(props, state) {
    
    if (props.options !== state.options) {
      let optionsArray = [];
      if (typeof props.options[0] === "object") {
        props.options.map((value, index) => {
          let key = value[props.optionKey];
          let label = value[props.optionLabel];

          optionsArray.push({ key: key, label: label });
        });
      } else if (typeof props.options[0] === "string") {
        props.options.map((value) => {
          optionsArray.push({ key: value, label: value });
        });
      }

      return {
        options: optionsArray
      };
    }

    return null;
  }

Sandbox link :- https://codesandbox.io/s/wizardly-rain-zbf7e?file=/src/DropdownMultiSelect.js

Upvotes: 1

Related Questions