How to get data from Material-UI TextField?

Learn how to use TextField Component of Material-UI and use it in your React Projects

Full Transcript

Hello folks, it Harit from bonsaiilabs. Today I will show you how you can get the data from Material-UI's TextField component and use in your React projects.

I will open up codesandbox and create a new sandbox based on the Official React template. I will make change to heading to make sure it reflects correctly in the output. Then, I will add a dependency of @material-ui/core to the project.

Let me quickly change the font size of the editor to make sure you can see the code well. Next, I will import the TextField component from @material-ui/core library. Then, I will add the TextField component to our render and add a value of bonsaiilabs to it. With that, we can see our TextField appeared on the output window. I will add a variant property to TextField to have a rounded corners on it.

Now, as you can see, when I click inside the TextField, I am not able to update the value, no matter what I type. This is because the value of this TextField is fixed. To make it variable, we need to keep this in the state. I will import useState React hook from React. Then I will add a new variable called value and a corresponding function called setValue by calling useState and setting the initial value to be empty string. I will now update TextField component to use value variable instead of hardcoded value of bonsaiilabs. With that, we see that textfield is now empty. And I am still not able to update it.

For that, I need to use onChange attribute of TextField component which accepts a handler function. I will add a new function called handleClick, which takes an event e as argument, and prints the value passed to event on the console using e.target.value. Then, I will pass this handleChange to onChange attribute. Let's test it now.

I will open the console tab here. Now, as I type in the text box, the characters are appeared on the console, but still not updated in the TextField. This is because we have not set the value for value variable. I do that now by calling setValue method inside handleClick and passing the value e.target.value to it.

With that, now as I type in the TextField, it gets updated in the component and also logged on the console.

Great! so you now know how to get the value from Material-UI's TextField component. Great! If you want us to cover more topics and specific questions, leave the comment below and we will add them to our queue for future videos.

Keep creating good thing! See you next time.