Now we can import the Form component in the App component, the main component of the application.

Remember that in the Form component we require a onSubmit prop. We must pass a function to this prop, so that we can add the new card to the list of cards.

Where is the list of cards maintained? In the App component state.

So we first include useState, so we can use hooks, and we call it to generate the array of cards. We initialize the state property to [], an empty array.

We add it to App, passing a method to add a new card to the list of cards, addNewCard, as its onSubmit prop:

import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import Form from './components/Form'
import CardList from './components/CardList'

const App = () => {
  const [cards, setCards] = useState([])

  addNewCard = cardInfo => {
    //...
  }

  return (
    <div>
      <Form onSubmit={addNewCard} />
      <CardList cards={cards} />
    </div>
  )
}

When addNewCard is called, we are getting the information in its only parameter, cardInfo. We can call setCards(), passing a new array of cards which we get by calling concat() on cards. This method does not alter cards, instead it returns a new array with the old cards plus the new one:

addNewCard = cardInfo => {
  setCards(cards.concat(cardInfo))
}

Finally we render the app:

ReactDOM.render(<App />, document.getElementById('app'))

Here is the full source code of our little React app:

import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import Form from './components/Form'
import CardList from './components/CardList'

const App = () => {
  const [cards, setCards] = useState([])

  const addNewCard = cardInfo => {
    setCards(cards.concat(cardInfo))
  }

  return (
    <div>
      <Form onSubmit={addNewCard} />
      <CardList cards={cards} />
    </div>
  )
}

const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)

That’s it! The application should now be fully working.

The complete example code, with the live app running, can be seen at https://codesandbox.io/s/qxpw3p1z4w


Go to the challenges