Using React Hooks to Get Input Value

Tulusibrahim
Geek Culture
Published in
3 min readMay 23, 2021

Hi! Today we will learn how to use react hooks in a simple way in order to get strong basic fundamental in react hooks.

The first thing we need to set up is of course react JS environment which you can refer to their documentation. If all is ready, then we are good to go!

First Step

Lets open up project file then open App.js file, there you can start by importing react and hooks useState so we can use it later. Here is how it looks.

Importing React and hooks
Importing React and hooks

Next is creating function called App, here we using functional component so it is aligned because we are going to use react hooks.

Creating functional component

Don’t forget to import it in the end of our code so it does not produce error.

Second Step

Declare hooks.

There we define name, setName. Name is the variable that we can use to display the value it has. Meanwhile setName is the setter method that we can use to change the value of name. useState is to define the initial value of the Name, it can be empty string, empty array, boolean, etc. To get better explanation of react hooks, you can refer to their docs.

Third Step

We need to provide return inside our App component so it will display something to the screen.

Add return

Looks terrible? yes. Calm down, I’ll explain it.

  • So the first thing is we create a div tag, which will wraps up all other element. There I added some style to the div tag.
  • Next is we define two input tag, a button with some placeholder in it
  • Then we define onChange props inside input tag. Inside onChange props we define anonymous function that has e parameter, so then we can get access to the value inside input tag. (The anonymous function is using arrow function, you can check it through W3School if you’re not familiar yet with it.)
  • Then inside anonymous function, we call the setter method that I already explain before, and we also pass the e parameter inside setter method, so the value of name, password is change every time the value inside input tag is changing.
  • There I also add a button with handleInput method just to console.log it to make sure everything is works.
  • Beneath the button, I added ternary operator to show some text if the name variable is filled with something.

Here is the looks of the whole code that we write so far.

The whole code

Wrap’s up! Those three simple step is enough to use hooks in simple way just to get started and get solid basic understanding about react hooks. Thank you for reading up to this point, see ya! ✨

--

--

Tulusibrahim
Geek Culture

Frontend engineer, usually post some thought once in a while.