{inputs.map((input, index) => (
handleInputChange(e.target.value, index)}
placeholder={`Input ${index + 1}`}
/>
{index !== 0 && ( // Do not show delete button for the first input
removeInput(index)} />
)}
))}
}>
Add Input
)
}
export const DynamicRadioInputList = React.memo(({defaultInputs, defaultSelected=null, onChange}) => {
const [inputs, setInputs] = useState(defaultInputs || [""]) // Initialize with one input
const [selectedRadio, setSelectedRadio] = useState(defaultSelected) // Tracks selected radio button
useEffect(() => {
setInputs(defaultInputs || [""])
}, [defaultInputs])
useEffect(() => {
setSelectedRadio(defaultSelected)
}, [defaultSelected])
useEffect(() => {
if(onChange){
onChange({inputs, selectedRadio})
}
}, [selectedRadio, inputs])
// Add a new input
const addInput = () => {
setInputs([...inputs, ""])
}
// Remove an input by index, but keep the first one
const removeInput = (index) => {
const newInputs = inputs.filter((_, i) => i !== index)
setInputs(newInputs)
// Adjust selected radio if necessary
if (selectedRadio >= newInputs.length) {
setSelectedRadio(newInputs.length - 1)
}
}
// Update input value
const handleInputChange = (value, index) => {
const newInputs = [...inputs]
newInputs[index] = value
setInputs(newInputs)
}
// Handle radio button selection
const handleRadioChange = (e) => {
setSelectedRadio(e.target.value)
}
return (
{inputs.map((input, index) => (
handleInputChange(e.target.value, index)}
placeholder={`Input ${index + 1}`}
/>
{index !== 0 && ( // Do not show delete button for the first input
removeInput(index)} />
)}
))}
}>
Add Input
)
})
/**
* defaultWeightMapping structure: {0: {gridNo: 0, weight: 0}}
*/
export const DynamicGridWeightInput = React.memo(({value, onChange, gridInputProps, weightInputProps}) => {
const [weightMapping, setWeightMapping] = useState(value) // Initialize with one input
useEffect(() => {
setWeightMapping(value || {})
}, [value])
useEffect(() => {
if(onChange){
onChange(weightMapping)
}
}, [weightMapping])
// Add a new input
const addInput = () => {
const newObjectIndex = Object.keys(weightMapping).length
setWeightMapping({...weightMapping, [newObjectIndex]: {gridNo: 1, weight: 0}})
}
// Remove an input by index, but keep the first one
const removeInput = (index) => {
const newInputs = { ...weightMapping }; // Create a shallow copy
delete newInputs[index]; // Remove the entry by key
setWeightMapping(newInputs); // Update state
}
// Update input value
const handleGridNoChange = (index, gridNo, weight) => {
const newInputs = {...weightMapping}
newInputs[index] = {
weight,
gridNo
}
setWeightMapping(newInputs)
}
return (