Skip to content
Advertisement

React JS custom table – handling select dropdown in table

A bit of context for this table – I want to create a table where user can select an option in the dropdown on the table header and compare. So this table has two columns and each column represents the data that’s been selected.

What I want to achieve is when one is selected say business in column one, how can I disable business / prevent it from being selected in column 2? As it doesn’t make sense to compare two of the same ones.

Also is there a better way to handle the onChange for the two select dropdowns? At the moment I have two methods and they are quite similar. I’ve tried to have only one onChange method but was not able to prevent both from changing when one is selected.

Here’s what I’ve done so far my table:

JavaScript

Here’s a working codesandbox for a full view

Advertisement

Answer

You need to keep the dropdown data in a variable, but as you initiating it in const data = .. it will recreates every time when the components get rendered, so you need to keep it in a useState or use useMemo

useState: this is good if you want to change the data, for ex: add another option

JavaScript

useMemo: this is good if you are not willing to change the options.

JavaScript

and then I need two variables to hold the options for each dropdowns

JavaScript

now when we rendering the options it should be like

JavaScript

here is the demo

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement