Home > Software engineering >  React dynamic select with button
React dynamic select with button

Time:11-30

I have an object array that looks like this:

const polls = [
    {
        title = "poll1",
        options = "option1;option2;option3"
        returnAddress = "xYn38akn[...]"
    },
    {
        title = "poll2",
        options = "optionA;optionB;optionC"
        returnAddress = "nJb3enH[...]"
    },
]

what I want to do is based on this array of object, to add a select-element (dropdown) with the possible options and a button, that calls onSend(returnAddress, selectedOption) with the returnAddress of the corresponding poll and the selected option.

Is it possible, to dynamically create this select and button per poll, so that every select has only the possible option of the corresponding poll and the button calls the onSend method with the selected option from the select and the returnAddress of the corresponding poll?

I've managed to get it to work when there is only one poll by having a state and setting it in the select:

const [selectedOption, setSelectedOption] = useState('')

function handleSelectedOptionChange(event: { target: { value: React.SetStateAction<string>; }; }) { 
    setSelectedOption(event.target.value);
}

[...]

<Select 
  [...]
  value={selectedOption}
  onChange{handleSelectedOptionChange}
  [...]
>

but of course this doesn't work with multiple polls... Sorry if that is a dumb question, it's the first thing I'm trying in React :-)

Thanks in advance!

CodePudding user response:

const [selectedOption, setSelectedOption] = useState([]);

function handleSelectedOptionChange(event: { target: { value: React.SetStateAction<string>; }; }) { 
    setSelectedOption(event.target.value);
}

[...]
polls.map((poll) => {
    const options = poll.options.split(';').filter(item => item.trim());
    return (
      <Select
        value={selectedOption[index] || undefined}
        onChange{e => handleSelectedOptionChange(e, poll.returnAddress)}
        [...]
      >
          {
            options.map(option => (
              <Option key={option}>{option}</Option>
            );
          }
      </Select>
    );
});

CodePudding user response:

You can simply start your selectedPol with null to depict no pol selected. And based on that once you select, you can dynamically switch between options.

Here is the code that I have typed for the usecase

Go to https://ikqdn.csb.app/select in Codesandbox Browser or directly click this link to open it.

https://codesandbox.io/s/happy-swartz-ikqdn?file=/src/App.js

I hope this is what you require

  • Related