Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Components as data

Components as data

Ever had to manage form state without a dependency? In this brief talk, we'll learn to handle dynamically generated form components, with the goal of thinking about our React components as Data. This gives us the ability to create even more dynamic and powerful react applications.
The power of components lies in its use. Thinking about React components as Data enables us to build and manage, highly dynamic react applications seamlessly. By the end of this talk, we should understand and appreciate components as data by walking through a dynamically generated form.

Orjiewuru Kingdom Isaac

February 06, 2018
Tweet

More Decks by Orjiewuru Kingdom Isaac

Other Decks in Programming

Transcript

  1. 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
  2. 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
  3. To be considered: ▹ Simple data model for a group

    of form inputs ▹ Managing the states of the inputs ▹ Validating the inputs 5
  4. 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
  5. 7 this.state = { education: [ { name: '', start:

    '', end: '' }, ] } School name Start year End year Add more
  6. Managing state Use array methods concat() and filter() to add

    and remove items(form input groups) dynamically. 8
  7. Adding items Items are added via concat(). The new array

    is the representation of our form inputs. 9
  8. Adding items handleAdd = () => { this.setState({ education: this.state.education

    .concat([{ name: '', start: '', end: '' }]) }); } 10
  9. 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
  10. Removing items 13 Items are removed via filter(). The returned

    array is a representation of our current form state.
  11. Removing items handleRemove = (index) => { this.state.education.length > 1

    && this.setState((currentState) => ({ education: currentState.education.filter((education, educationIndex) => index !== educationIndex) })); } 14
  12. Validation We can add custom validation for these dynamic form

    inputs. Validation can be found in Github gist 15