Set dynamic input fields in React

 Example for Input type text:


const [videoUrls, setVideoUrls] = useState([{ id: 0, url: '' }])
const addVideoField = () => {
setVideoUrls([...videoUrls, { id: videoUrls.length, url: '' }])
}

const handleVideoUrlChange = (id, value) => {
const updatedUrls = videoUrls.map(video => (video.id === id ? { ...video, url: value } : video))
setVideoUrls(updatedUrls)

<div id=''>
<Grid container direction='row' alignItems='normal' spacing={4} sx={{ pl: 5, pr: 5, pt: 3, pb: 2 }}>
<Grid
item
sm={12}
sx={{
pl: 5,
pr: 5,
pt: 3,
pb: 2
}}
>
{videoUrls.map((field, index) => (
<Box
key={field.id}
display='flex'
flexDirection='row'
alignItems='end'
justifyContent='center'
sx={{ mb: index < videoUrls.length - 1 ? 2 : 0 }}
>
<TextField
label={`YouTube Link ${index + 1}`}
value={field.url}
onChange={e => handleVideoUrlChange(field.id, e.target.value)}
error={Boolean(errors?.[`videoTutorialUrl_${field.id}`])}
helperText={errors?.[`videoTutorialUrl_${field.id}`]?.message}
InputProps={{
style: { backgroundColor: 'white' },
startAdornment: (
<InputAdornment position='start'>
<YoutubeLinkIcon />
</InputAdornment>
)
}}
fullWidth
sx={{
'& .MuiInputBase-root': {
backgroundColor: 'white'
}
}}
/>
{index === videoUrls.length - 1 && (
<Button
variant='contained'
color='primary'
onClick={addVideoField}
sx={{
ml: 4,
mb: 2,
maxWidth: 36,
maxHeight: 36,
minWidth: 36,
minHeight: 36,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
borderRadius: '5px'
}}
>
<AddIcon style={{ fill: 'white' }} />
</Button>
)}
</Box>
))}
</Grid>
</Grid>
</div>

Comments

Popular posts from this blog

React Native

Clone GitHub repository to SourceTree

Commands for setting up and running a development environment