PLATFORM
  • Tails

    Create websites with TailwindCSS

  • Wave

    Start building the next great SAAS

  • Pines

    Alpine & Tailwind UI Library

  • Auth

    Plug'n Play Authentication for Laravel

  • Designer comingsoon

    Create website designs with AI

  • DevBlog comingsoon

    Blog platform for developers

  • Static

    Build a simple static website

  • SaaS Adventure

    21-day program to build a SAAS

Working with input fields in React

Working with input fields in React

React JavaScript library is a leading tech when it comes to web app development. With its component-driven development ecosystem, we can develop intuitive user interfaces with powerful features. Talking about features, one of the most extensively used elements in any web application is forms. Forms are used in registration, logins, or any other task which requires data input. And when it comes to forms, the most extensively used element is the Input field. Input fields are an important element to the front end web development as it interacts with the user to get their information. It is the best way to take inputs from the end-users.

In this tutorial, we are going to learn some of the workings of the input field in React environment. The idea is to start off with selecting the entire text inside the text input. Then, we are going to learn how to fetch the value from the input field so that we can use it programmatically in any logical operations. Lastly, we will also learn how to clear the input field. These are some basic as well as essential operations that we need to know about working with the input field in React.

So, let's get started!

Selecting all text in the input field with React

In this section, we are going to learn how to select the text inside an input field in a React app. For that, we are going to take the help of a button trigger.

In React, in order to select the whole text in an input field, we can use e.target.select() method.

The typical example of using this method to select the text in an input field of a functional React component is provided in the code snippet below:

import React from "react";

export default function App() {
  const handleClick = (e) => {
    e.target.select();
  };

  return (
    <div className="App">
      <input type="text" onClick={handleClick} value="King" />
    </div>
  );
}

Here, we have kept a handleClick function in an onClick event of input field. On clicking the input field, the function triggers also triggering the select() method which selects the entire text in an input field.

Another way by which we can select the text in an input field is by using the useRef hook. By initializing a useRef instance and assigning it to the input field we can get the reference to the input field configs. Then, we can select the entire text in the input field by using the select() method of the current object provided by in useRef variable instance i.e. inputRef as shown in the code snippet below:

import React, { useRef } from "react";

export default function App() {
  const inputRef = useRef(null);

  const handleClick = () => {
    inputRef.current.select();
  };

  return (
    <div className="App">
      <input ref={inputRef} onClick={handleClick} value="King" />
    </div>
  );
}

Similarly, we can also select the text by focusing on an input field. The result of our implementation is shown in the demo below:

select_all_text.gif

Fetching an input field value in React

In this section, we are going to learn how to fetch the value entered in the input field programmatically in a React app ecosystem. The process is simple and easy to understand. A standard example is shown in the code snippet below:

import React from "react";

class App extends React.Component {
  state = {
    name: ""
  };

  handleInput = (event) => {
    this.setState({ name: event.target.value });
  };

  logValue = () => {
    console.log(this.state.name);
  };

  render() {
    return (
      <div>
        <input onChange={this.handleInput} placeholder="Enter your name" />
        <button onClick={this.logValue}>show value</button>
      </div>
    );
  }
}
export default App;

Here, we have initialized a state variable called name. By using the onChange event on input field, we can trigger the function handleInput each time the value in input field changes. As handleInput function triggers, it sets the value in input field to the name state. Then, we can access the value of input field from the state variable anyway we like.

Hence, the result of our implementation is shown in the demo below:

result.png

Using Hooks

We can also use the useState hook to initialize a state variable and store the input field value just as in the process above. Here, the useState value is used in a functional component to initialize the states. All other processes are similar to the above one.

The example of using a hook is shown in the code snippet below:

import React, { useState } from "react";

 export default() => {
  const [name, setName] = useState(" ");

  const handleInput = event => {
    setName(event.target.value);
  };

  const logValue = () => {
    console.log(name);
  };

  return (
    <div>
      <input onChange={handleInput} placeholder="Enter name"/>
      <button onClick={logValue}>Print value</button>
      <p>{name}</p>
    </div>
  );
}

Clearing the input field value

Since we now know how to select and fetch the value entered in the input field, we might also learn how to clear them as well in React app. Clearing the input field is an essential feature for any form elements in a React app. It provides a good user experience and easiness to delete values from the input field.

The process is simple. We initialize a state that stores the input field value upon typing. Then, we implement a button whose onClick event triggers a function in which we set the state to empty value. The empty state thus reflects in the input field as well clearing all the values from it. The coding implementation for this is shown in the code snippet below:

import React, { useState } from "react";

 export default() => {
  const [name, setName] = useState(" ");

  const handleInput = event => {
    setName(event.target.value);
  };

  const logValue = () => {
    console.log(name);
  };
  const ClearVal = () => {
    setName("")
  };
  return (
    <div>
      <input onChange={handleInput} value={name} placeholder="Enter name"/>
      <button onClick={logValue}>Print value</button>
      <button onClick={ClearVal}>Clear value</button>
      <p>{name}</p>
    </div>
  );
}

Hence, on pressing the clear button, the value from the input field is cleared out as shown in the demo below:

clear text

Hence, we have successfully learned how to select, fetch and clear the text input value in React app.

Conclusion

The main goal of this tutorial was to get familiar with input field workings in React environment. The basic operations such as selecting the text in the input field, fetching its value as well as clearing the input field are essential operations that we can do with input fields to provide a better user experience to users while they are entering some information in the input fields. The examples provided are the most simple ones from which you can understand how to make use of input fields in class as well as a functional component of React ecosystem.

Comments (0)

loading comments