Home > Net >  Multiple comboboxes value in React
Multiple comboboxes value in React

Time:03-11

I am creating a page where the user choose to upload some files,then choose the file type of each file from a combo box then submit. 'reports' are the files the user chosed to upload, i mapped over them to show them in rows then the user can choose for each file the crossponding file type. How to get the value in the combo box for each file the user uploaded? My code runs for only one file but how can be edited to be for multiple comboboxes?

enter image description here

const [fileType, setFileType] = useState('');

    const fileChangeHandler = (event:React.ChangeEvent<HTMLSelectElement>) => {
        
        setFileType(event.target.value);
   
    }
return (
<div>
        {reports.map((report, i) => (
            <div className="file-row" key={i}>
                <div>{report.name}</div>
                <div>
                    <select className='frm-select' value={fileType} onChange={fileChangeHandler}>
                        <option value="" selected disabled hidden>Select File Type</option>
                        {fileTypeOptions.map((option) => (
                            <option key={option.id}>{option.FileName}</option>
                        ))}
                    </select>
                </div>
                {renderFileRow(report, i,fileType)}
            </div>
        ))}
    </div>
);

CodePudding user response:

I'd suggest you use a map (like an object but more dynamic) instead of a plain string. I'm not sure you have report.id or not, so I'm using report.name for this example

//create an empty map for all file types
const [fileTypes, setFileTypes] = useState<{ [key: string]: string }>({});

    const fileChangeHandler = (event:React.ChangeEvent<HTMLSelectElement>, reportName: string) => {
        //it will return an object for all file types
        setFileTypes({
           ...fileTypes,
           [reportName]: event.target.value
        });
   
    }
return (
<div>
        {reports.map((report, i) => (
            <div className="file-row" key={i}>
                <div>{report.name}</div>
                <div>
                    <select className='frm-select' value={fileTypes[report.name]} onChange={(e) => fileChangeHandler(e, report.name)}>
                        <option value="" selected disabled hidden>Select File Type</option>
                        {fileTypeOptions.map((option) => (
                            <option key={option.id}>{option.FileName}</option>
                        ))}
                    </select>
                </div>
                {renderFileRow(report, i,fileType)}
            </div>
        ))}
    </div>
);

The final results of fileTypes will be like this

{
   "report name 1": "pdf",
   "report name 2": "image"
}

Here is how we access file type for each report

fileTypes[report.name]
  • Related