Slide 1

Slide 1 text

Components as data

Slide 2

Slide 2 text

HELLO! I’m Orjiewuru Kingdom Software developer - Andela / CommonBond You can find me at @kingisaac95 2

Slide 3

Slide 3 text

Components As Data “The core premise for React is that UIs are simply a projection of data into a different form of data.” - Sebastian Markbåge This talk is not about react theoretical concepts, rather I want to share what I learnt while researching on how to make forms dynamic in React 3

Slide 4

Slide 4 text

Components As Data When the form needs to by dynamic, it sometimes posses issues with regards to managing their state and validation. How can thinking of these atomic components as data help? 4

Slide 5

Slide 5 text

To be considered: ▹ Simple data model for a group of form inputs ▹ Managing the states of the inputs ▹ Validating the inputs 5

Slide 6

Slide 6 text

Data model One way is to use an array of objects. With an array, we can easily add, remove and update the details of our form inputs. The array will contain objects representing the form groups. 6

Slide 7

Slide 7 text

7 this.state = { education: [ { name: '', start: '', end: '' }, ] } School name Start year End year Add more

Slide 8

Slide 8 text

Managing state Use array methods concat() and filter() to add and remove items(form input groups) dynamically. 8

Slide 9

Slide 9 text

Adding items Items are added via concat(). The new array is the representation of our form inputs. 9

Slide 10

Slide 10 text

Adding items handleAdd = () => { this.setState({ education: this.state.education .concat([{ name: '', start: '', end: '' }]) }); } 10

Slide 11

Slide 11 text

Handling changes Update the individual items in the objects using their index 11

Slide 12

Slide 12 text

Handling changes handleChange = (event, index) => { const updatedEducation = this.state.education.map((education, educationIndex) => { if (index !== educationIndex) return education; return { ...education, [event.target.name]: event.target.value } }); this.setState({ education: updatedEducation }); } 12

Slide 13

Slide 13 text

Removing items 13 Items are removed via filter(). The returned array is a representation of our current form state.

Slide 14

Slide 14 text

Removing items handleRemove = (index) => { this.state.education.length > 1 && this.setState((currentState) => ({ education: currentState.education.filter((education, educationIndex) => index !== educationIndex) })); } 14

Slide 15

Slide 15 text

Validation We can add custom validation for these dynamic form inputs. Validation can be found in Github gist 15

Slide 16

Slide 16 text

Links JSFiddle - bit.ly/dynamicformdemo Github gist - bit.ly/dynamicformgist Inspired by @goshakkk’s article - bit.ly/2FTmuvX 16

Slide 17

Slide 17 text

17 Thank You!