AOUADI Slim
AOUADI Slim

Reputation: 467

Mapping over an array starting from the next index

i have an array of strings and i have a default input text as first input to enter a module title and when i press on the button add it adds another input field so i can add another module title inside that array but the problem is that i couldn't find a way to do it i thought i can push the first input value in like the index 0 and then start looping on the array using map function over that array to add inputs but i didn't know how to do it or how to tell it to start like from the index 1 not 0 i hope you got what i mean

my code portion

         <TextField
                    style={{ marginLeft: '15%' }}
                    hintText="Module Title"
                    floatingLabelText="Module Title"
                    onChange={handleFormChange('moduleTitle')}
                    defaultValue={values.moduleTitle}

                />
                <br />


                {




                    // ADD If on Array length 
                    values.modules.map((module, index) => {

                        return (

                            <div key={index}>


                                <TextField
                                    style={{ marginLeft: '15%' }}

                                    hintText="Module Title"
                                    floatingLabelText="Module Title"
                                    onChange={e => this.props.handleChange(e, index)}
                                />

                                <input type="button" value="remove" onClick={() => this.props.removeModule(index)} />
                                <br />
                                <br />
                            </div>



                        )
                    })
                }


                <Fab color="primary" onClick={(e) => this.props.addModule(e)} aria-label="add" style={{ marginLeft: '45%' }}>
                    <AddIcon />
                </Fab>

what i want to do is when i press the button Add it take the value from that default first input and push it in the array and then another inputs appears and it goes like that i'am really stuck hope you can help me

Upvotes: 0

Views: 36

Answers (2)

vivalldi
vivalldi

Reputation: 521

If you're strictly looking to skip over the first item you can destructure the array to get all remaining elements and map over those.

const [, ...allButFirst] = values.modules;

allButFirst.map(module => (<div>...</div>));

Upvotes: 3

Auskennfuchs
Auskennfuchs

Reputation: 1737

The easiest way is to check the index:

values.modules.map((module, index) => {
    if(index === 0) return null
    return (
      <div ...>
      ...
    )
})

Maybe there is a more elegant solution to this

Upvotes: 0

Related Questions