ReactJS - InputEvent Handler



The InputEvent interface is commonly used in web development for creating features such as real-time validation for form fields, rich text editors, or any application that needs to track and respond to user input inside text-based content.

Syntax

<input onBeforeInput={e => console.log('onBeforeInput')} />

The onBeforeInput event type in React is important because it lets us collect and respond to changes in editable content. With a simple React application, we will look into the onBeforeInput event and its related features.

The onBeforeInput event alerts our React application when editable content changes, like when a user inputs, deletes, or formats text. It is especially useful for creating rich text editors, form fields, and other interactive text-based components.

Properties of InputEvent

Before we go into our small React application, let's look into the important properties of the InputEvent object, which is part of the onBeforeInput event.

  • data − The string of entered characters is stored in the data property. It can be empty if no text is inserted, such as when characters are removed.

  • dataTransfer − This property returns a DataTransfer object with information about adding or removing rich text or plain text data from editable content.

  • inputType − It specifies the sort of changes being made to the editable material, such as entering, removing, or formatting text.

  • isComposing − A Boolean value that shows whether the event is fired after compositionstart and before compositionend. This is important when dealing with text input in languages with complicated compositions.

Examples

Example − Logs the Data

Let's put this information to use by creating a small React application.

We will create a simple React app which logs the data property of the InputEvent when the onBeforeInput event is triggered. This will allow us to see the event in action.

import React from "react";

class App extends React.Component {
   render() {
      return (
         <div>
            <h1>React InputEvent Function</h1>
            <input onBeforeInput={(e) => console.log("onBeforeInput", e.data)} />
         </div>
      );
   }
}

export default App;

Output

react inputevent function

This is a basic React application. It creates a page with the headline "React InputEvent Function" and an input field.

When we type or make changes in the input field, an event called onBeforeInput is triggered. This event is used to keep track of what we type or change in the input area.

To record the event's data to the console, the code employs an arrow function (e) => console.log("onBeforeInput", e.data). So when we enter in the input box, the e.data section will display what we are typing in the console.

This code allows us to view what we are typing in an input field and is a simple example of using React with event handling.

Example − Character Counter

Here's another simple React application which shows the concept of the onBeforeInput event to create a character counter for an input field. This application will display the number of characters as we type in the input field −

import React, { Component } from "react";

class App extends Component {
   constructor() {
      super();
      this.state = {
         charCount: 0
      };
   }   
   onBeforeInput = (e) => {
      const inputText = e.target.value;
      const charCount = inputText.length;
      this.setState({ charCount });
   };   
   render() {
      return (
         <div>
            <h1>Character Counter</h1>
            <input
               type="text"
               onBeforeInput={this.onBeforeInput}
               placeholder="Type something..."
            />
            <p>Character Count: {this.state.charCount}</p>
         </div>
      );
   }
}

export default App;

Output

character counter 6

Example − Filter posts

Now we will create a simple app to show the posts which will be fetched from a public API. To use the React InputEvent handler function, we will add an input field that filters the posts as per the title as the user will enter in the text box. We will use the onInput event handler for this purpose −

import React, { useState, useEffect } from "react";

const App = () => {
   const [posts, setPosts] = useState([]);
   const [searchTerm, setSearchTerm] = useState("");   
   useEffect(() => {
      // Simulating API call
      fetch("https://jsonplaceholder.typicode.com/posts")
      .then((response) => response.json())
      .then((data) => setPosts(data))
      .catch((error) => console.error("Error fetching data:", error));
   }, []);
   
   const handleInput = (e) => {
      setSearchTerm(e.target.value);
   };
   
   const filteredPosts = posts.filter((post) =>
   post.title.toLowerCase().includes(searchTerm.toLowerCase())
   );
   
   return (
      <div>
         <h1>React API Fetch App</h1>
         <input
            type="text"
            placeholder="Search by title"
            onInput={handleInput}
         />
         <ul>
            {filteredPosts.map((post) => (
            <li key={post.id}>{post.title}</li>
            ))}
         </ul>
      </div>
   );
};

export default App;

Output

react api fetch app

In this app, I have added an input field that updates the searchTerm state using the onInput event handler. The posts are then filtered as per the title, and only the matching posts are displayed.

Summary

So the InputEvent is a useful tool for React developers that work with editable information. It enables us to collect and respond to changes in an easy way. We reviewed the InputEvent's essential characteristics and constructed a basic React application to show its use. The concept can be extended to create complex applications, such as rich text editors or interactive forms.

reactjs_reference_api.htm
Advertisements