3

I am trying Create a select field dynamically. When clicking the add button, it will dynamically add select fields. I have and issue where the values don't change.

My code can be viewed on codesandbox:
https://codesandbox.io/s/react-select-field-dynamically-uo4dy?file=/src/App.js

1
  • instead of option.value.target , it should be option.value; Commented Jul 9, 2021 at 12:08

2 Answers 2

1

Take a look at my changes:

Forked sandbox

// I added a 3rd argument for the name:    
const handleRoomChange = (option, index, name) => {
    const value = option.value; // you had this as 'const { value } = option.value' which dereferences value twice
    console.log(value);
    const list = [...roomInputs];
    list[index][name] = value; //you had this as list[index][value]
    setRoomInputs(list);
  };


// onChange passes the name as 3rd argument to handleRoomChange
<Select
   name="boardBasic"
    placeHolder="Board"
    value={options.value}
    onChange={option => handleRoomChange(option, i, "boardBasic")}
    options={options}
    styles={{
        menu: (provided) => ({ ...provided, zIndex: 9999 })
    }}
/>
Sign up to request clarification or add additional context in comments.

1 Comment

These changes do fix the problem, but I would recommend changing handleRoomChange's name if it is going to handle both room and board changes, to avoid confusion later on.
1

You have three problems that I can see.

First, you only have a handleRoomChange function that is trying to handle both room changes and board changes. You should probably have a handleBoardChange function, as well.

Second, if you output option to the console inside handleRoomChange, you will notice that option.value is a number. So, when you proceed to set list[index][value] to value, what you're saying is that you want (for example) roomInputs[1][1] to be 1. roomInputs[1] has no 1 property, which is why you will end up with the wrong properties inside your object on submission. You need to be setting roomInputs[1].roomType to value, instead (and the boardBasic property in your handleBoardChange method, when you write it).

Third, you are trying to use object destructuring to assign object.value to your value variable...but you're trying to destructure object.value instead of destructuring object. For this reason, value is undefined every time you run the function. Replace the assignment with const { value } = option; and you will start getting defined values back.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.