Hello World Master

Tutorials, articles and quizzes on Software Development

Ionic React > Articles

Using a Model to enter data in Ionic React

This article is associated with the following course
Introduction to Ionic React

In our Model, we want to create some text fields to add a new TodoItem onto our page.

Let’s use the IonInput for the Todo title and a IonTextArea for the description of the Todo item to add input fields.

...
<IonModal isOpen={showModal}>
   <p>This is modal content</p>
   <IonItem>
     <IonInput placeholder="Enter Todo Item"></IonInput>
   </IonItem>
   <IonButton onClick={() => setShowModal(false)}>Close Modal</IonButton>
</IonModal>
...

Now we need to make sure that our input and text area both use the useState hook so we get back the data inside them when we’re done.

...
const Home = () => {

  const [showModal, setShowModal] = useState(false);
  const [newTodo, updateNewTodo] = useState('');

...
<IonList>
  <IonItem>
    <IonInput value={newTodo} placeholder="Enter Todo Item" onIonChange={e => updateNewTodo(e.detail.value)></IonInput>
  </IonItem>
</IonList>

Notice that we use onIonChange instead of onChange.

Creating a submit button to add a new TodoItem

Finally we want to create a submit button to add a new todo item based on the information in our input box.

<IonModal isOpen={showModal} cssClass='my-custom-class'>
  <p>This is modal content</p>
  <IonList>
    <IonItem>
      <IonInput value={newTodo} placeholder="Enter Todo Item" onIonChange={e => updateNewTodo(e.detail.value)></IonInput>
    </IonItem>
  </IonList>
  <IonButton onClick={submitTodo}>Add todo</IonButton>
  <IonButton onClick={() => setShowModal(false)}>Close Modal</IonButton>
</IonModal>

Lets make sure to also create the submitTodo function. This function will add our todo information as an element in an array, reset the text input fields inside our model to be ready for when we want to add a new todolist item, and then finally close our model since we do longer need it once we press submit.

function submitTodo() {
  const listOfTodosClone = Object.create(todoItems, []);
  const newTodoItem = {title: newTodo};
  listOfTodosClone.push(newTodoItem);
  updateTodoItems(listOfTodosClone);
  updateNewTodo('');
  showModal(false);
}

Click here to view the code associated with this article