#13 How do we use Inputs in React? - Delightful React

#13 How do we use Inputs in React? - Delightful React

Handling form inputs is a very important part of building user interfaces and React offers a few options for inputs.

Asset_53.png

In this chapter, we will learn how to handle inputs in React and use the input to filter a list.

*Note: This article is a part of the Delightful React Series, as part of which, I am releasing one chapter every day for 25 days. Please support me in anyway you can! *


You can use this code sandbox embed as a starting point for this chapter. Fork it and follow the next instructions.


Let’s talk about form inputs and how they work and then let’s look at how React helps us manage inputs in forms.

Asset_43-1.png

HTML Forms

Forms are a means to allow users interact with apps. Chat servers, contact forms, posts in feeds are all made of Form elements.

Asset_54.png

  • Form elements like inputs, radio buttons, checkboxes allow users to enter information into our app and interact with it.
  • Inputs have various event listeners like focus, blur, change, etc that help app developers to react to user events.
  • Forms also have events like submit which can be used to react to a form submission by the user.

React Forms

  • React doesn’t interfere too much with the native behaviour of HTML Form Inputs by default (similar to how React manages other elements too).
  • By default, once React renders a form input, by default, it doesn’t do much else. You are on your own.

Uncontrolled Inputs

  • The default mode is called “uncontrolled” mode. As the name speaks for itself, React doesn’t control any of the input’s behaviour.
  • Let’s add an input element to our AllPosts component.
//pages/index.js

 function AllPosts() {
  return (
    <div>
      <div className="search-posts">
            <input type="text" value={searchText} />             
        </div>
      <div className="post-list">
        {BLOGPOSTS.map((blogPostObject) => {
          return (
            <ListItem
              key={blogPostObject.title}
              blogPostObject={blogPostObject}
            />
          );
        })}
      </div>
    </div>
  );
}

We want to filter out the posts based on the text typed in this input. The problem here is that, there is no easy way to get the text typed into the form elements.

Uncontrolled inputs aren’t as preferred because of this reason.

Controlled inputs with state

  • An alternative approach is to use controlled inputs. Controlled inputs are entirely controlled by React.
  • The value of these inputs can’t be changed except via React.
  • To make an input controlled, simply give it a value prop.

Arguments_to_a_function_Copy_5.png

Let’s give our input a value of “asdf”.

  • Now, even if we type something into the input, React doesn’t allow the value to stay and clears it instantly.

Well, the input is now, not type-able isn’t it?

Here comes the catch.

  • DOM Input events like “change” etc can still fire and we can use that to grab the new value that was just typed into the input before React cleared it.
  • All we need to do now, is to make our value prop of the input be this new value each time we type into the input.
  • This can be easily done by using a state variable. -
Let’s create a searchText state variable and update it’s value in the onChange event handler like so.
//pages/index.js

  function AllPosts() {
    const [searchText, setSearchText] = useState("");
    console.log(searchText)
    return (
      <div>
        <div className="search-posts">
            <input type="text" value={searchText} onChange={function(event){
              setSearchText(event.target.value)
            }}/>             
        </div>
        <div className="post-list">         
            ...
        </div>
      </div>
    );
  }
  • So now, we are able to type into our input and at the same time, we are also able to access the new value within the Component body.
  • And now, each time the state variable changes, our component rerenders and we can use this state variable to filter out our blogposts.

Filtering jobs with search input

  • To filter items in an array, we can use the Array filter method.
  • Like push, pop and map, filter is also one of the methods on all arrays in javascript.
  • The filter function runs through each item in the array with a predicate function. Using this predicate function, we can test whether an item satisfies a condition.
  • If the predicate function is true, then the value is filtered in, otherwise it is left out.

So let’s create a predicate function, to check if the title of a blogPost item includes the searchText.

//pages/index.js

  const [searchText, setSearchText] = useState("");
  const filteredBlogPosts = BLOGPOSTS.filter(blogPostObject => {
    // if searchText is blank then show all posts
    if(!searchText){
      return true;
    }
    if(blogPostObject.title.includes(searchText)){
      return true;
    }else{
      return false;
    }
  });
  • Of course, if searchText is empty, all items should return true in the function.

  • The filter method returns a new array with all the values it found to satisfy the predicate function.

  • We will use this new array to render our list items like so.
//pages/index.js

  {filteredBlogPosts.map((blogPostObject) => {
    return (
      <ListItem
        key={blogPostObject.title}
        blogPostObject={blogPostObject}
      />
    );
  })}

It works!

Group_3.png

Codesandbox Demo

Great work!

Awesome, our filtering logic is complete and we are able to sort our list items of blogposts in the home page using a search input that is managed entirely using State!

  • State is super powerful when used with inputs because it allows us to interact with the value of the input in the component's body itself in a very declarative manner.

Let's keep going!


"😲 But Bhargav, Are controlled inputs the only way to work with inputs in React? “

Definitely not. Uncontrolled inputs can also be used to work with React but they have a different approach.

Controlled form input libraries like Formik are very popular in the React ecosystem but new libraries based on uncontrolled form inputs like react-hook-form are also picking up today.

Thanks and Please support my work

  • Writing blog posts and making videos is an effort that takes many hours in my day. I do it because I love teaching and make great content.
  • However, I need your support too. Please support my work and follow my social accounts to help me continue to make great content.
  • Here are my social links.

Follow me on Twiter

Subscribe to my channel on Youtube

Thank you!