"Can you share a method to extract the value from a TextField component in a React hook-based Material-

Currently, I am using Material-UI within a React project and have a component set up like this:

const UserDetail = (props: ListDetailProps) => {
    const oldpassword = useRef<TextFieldProps>(null);
    const newpassword = useRef<TextFieldProps>(null);
    const againpassword = useRef<TextFieldProps>(null);
    const handlePasswordChange = async () => {
        console.log(newpassword.current?.value); //expecting the password value but getting undefined
        console.log(againpassword.current?.value); //expecting the password value but getting undefined
    }
    return (<>
        <p>old password: <TextField ref={oldpassword} label="old password" type="password" /></p>
        <p>new password: <TextField ref={newpassword} label="new password" type="password" /></p>
        <p>new password: <TextField ref={againpassword} label="new password again" type="password" /></p>
        <button onClick={handlePasswordChange}>submit</button>
    </>
    )
}

I am trying to retrieve the value of the TextField reference but it returns as undefined. Is there a way to obtain the value of the TextField reference?

I previously came across an answer on: React: How to get values from Material-UI TextField components,

However, that solution was for a Form button. If I do not have a form, how can I achieve this?

Answer №1

Make sure to utilize inputRef instead of ref.
This is important because inputRef will provide a reference to the input element.

const UserDetail = (props: ListDetailProps) => {
    const oldpassword = useRef<TextFieldProps>(null);
    const newpassword = useRef<TextFieldProps>(null);
    const againpassword = useRef<TextFieldProps>(null);
    const handlePasswordChange = async () => {
        console.log(newpassword.current?.value)    //expect the password value but undefined get
        console.log(againpassword.current?.value)  //expect the password value but undefined get
    }
    return (<>
        <p>old password: <TextField inputRef={oldpassword} label="old password" type="password" /></p>
        <p>new password: <TextField inputRef={newpassword} label="new password" type="password" /></p>
        <p>new password: <TextField inputRef={againpassword} label="new password again" type="password" /></p>
        <button onClick={handlePasswordChange}>submit</button>
    </>
    )
}

For more information, you can check out the material-ui TextField API documentation

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I have developed a Next.JS-Redux application that simultaneously compiles two pages

Upon redirecting with window.location.href, I encountered the following compilations in the terminal: wait - compiling /login/verify (client and server)... wait - compiling /login (client and server)... Instead of going to /login/verify as expected, it ...

Adding spacing breakpoints in Material-UI 5 sx properties

Currently in the process of updating my components to utilize the latest MUI version. I have been converting old classes into the sx props and I find this new styling method to be more readable in my opinion. However, one thing that concerns me is handl ...

Incorporating a Material UI Icon into a FontIcon Material-UI element within a React application

I am attempting to showcase a Material-UI Icon using a React Material-UI FontIcon component. Here is my code: <FontIcon className="material-icons"/> Help </FontIcon> Instead of displaying the icon on the screen, only text is shown. Th ...

The Karma testing feature in Angular Quickstart encounters issues right from the start

When attempting to run karma tests after a clean install of the official Angular quickstart on Windows 10, I encountered an issue. Following a series of four commands, here is what happened: C:\projects\temp>git clone https://github.com/angul ...

I am unable to utilize autocomplete with types that are automatically generated by Prisma

Currently, I am working on a project utilizing Next and Prisma. Within my schema.prisma file, there are various models defined, such as the one shown below: model Barbershop { id String @id @default(uuid()) name String address String ...

JavaScript file encountering a Typescript issue with a property defined in a subclass

Currently, I am utilizing Typescript to validate my Javascript files. One issue I have encountered is that when I inherit from a class, Typescript does not recognize the types of the properties in the parent class. I am unsure if I am overlooking something ...

Ways to prevent decreasing the value below zero in ReactJS?

I have created two buttons, one for increasing and another for decreasing a counter value. However, when I click on the minus button, it should not display negative values. But in my case, when I click on the minus button (initially at zero), it shows -1, ...

After the installation of Storybook, there is a duplicate identifier error that arises with 'LibraryManagedAttributes'

Upon running the command npx storybook@latest init for setting up Storybook, which results in modifying package.json, I encounter an issue where I cannot run the project using npm due to: Error: node_modules/@types/react-dom/node_modules/@types/re ...

How come this mocha test is exceeding its timeout limit when making a basic call with mongoose?

Trying to write a simple assertion for an asynchronous database method: describe('User Repository', () => { describe('findById', () => { it('Returns a user that can be found in the database by ID', async () => { ...

The integration of AsyncStorage with the web application is facing challenges

We are in the process of developing an app using react-native, where we retrieve data such as login/signup through our custom X-sdk. The X-sdk acts as a middleware/api fetcher that interacts with the backend api to obtain necessary information. In order to ...

Inability to assign a value to an @input within an Angular project

I recently started using Angular and I'm currently trying to declare an input. Specifically, I need the input to be a number rather than a string in an object within an array. However, I'm encountering difficulties and I can't figure out wha ...

What causes an array to accumulate duplicate objects when they are added in a loop?

I am currently developing a calendar application using ExpressJS and TypeScript. Within this project, I have implemented a function that manages recurring events and returns an array of events for a specific month upon request. let response: TEventResponse ...

Having trouble setting the state of an array using NextJS useState?

I'm facing an issue where the array saved to a useState state is not updating properly. Despite properly returning values for the variable first, the variable "data" remains an empty array. Interestingly, adding a console.log("restart") statement und ...

What is the best way to add a style to the currently active link on a NavLink component using the mui styled() function

I have a custom NavLink component that I want to style with an ".active" class when it is active. However, I am not sure how to achieve this using the "styled()" function in MUI. Does anyone know how to accomplish this? Below is the code for my custom Nav ...

Secure higher order React component above class components and stateless functional components

I have been working on creating a higher order component to verify the authentication status of a user. Currently, I am using React 15.5.4 and @types/react 15.0.21, and below is a simplified version of my code: import * as React from 'react'; i ...

When incorporating React-query with Next.js and utilizing hydration configuration for server-side rendering, cached results are not utilized, leading to the need to perform another fetch request

While working on my nextjs app, I decided to implement react-query with SSR/SSG and went through several tutorials. I opted for the hydration configuration over the initialData approach as it seemed more efficient. Following the instructions in the react- ...

Error: Unable to locate module '@material/core/Grid'

After cloning a repository that is built with MUI, I noticed that certain components were already imported and working seamlessly. These components include: import Card from '@mui/material/Card' import CardActions from '@mui/material/CardAct ...

Establishing the exterior façade prior to generating the Docker image

I am currently new to Docker and in the process of dockerizing some applications. The project structure consists of: -PlayProject -------app ----------controllers ----------models ----------views -------ci -------conf -------project -------public ---- ...

What is the best way to sort through an array depending on a specific sequence of elements provided

I am trying to create a custom pipe in Angular 5 that filters an array of events based on a given sequence. For instance, if my data is: ["submit", "click", "go_back", "click",...] I want to filter this data based on up to three inputs. If input ...

Creating a FusionCharts time series with a sleek transparent background

Currently, I am attempting to achieve a transparent background for a time-series chart created with FusionCharts. Despite trying the standard attributes that usually work on other chart types and even hardcoding a background color, none of these seem to af ...