Casa > I > In React, How Do You Get Values From Material-Ui Textfield Components?

In React, how do you get values from Material-UI TextField components?

I assume you are referring to this component

The short answer: TextField has an onChange property that uses an event argument. So you would want to do something like this:

  1. ...props, 
  2. onChange={(event) => someHandlerFunction(event.target.value)} 
  3. /> 

onChange takes one argument that references the event, to get the value from this argument you use event.target.value

Long Answer:

There are two ways of doing this, one would be to use state in a traditional component, the other would be to use the new React Hooks API. I’ll show both implementations.

Traditional using state

  1. import React from 'react' 
  2. import { TextField } from '@material-ui/react' 
  3.  
  4. class MyComponent extends React.Component { 
  5. state = { 
  6. myValue: '', 
  7.  
  8. handleChange = (e) => this.setState({ 
  9. myValue: e.target.value 
  10. }) 
  11.  
  12. render() { 
  13. return ( 
  14. value={this.state.myValue} 
  15. onChange={this.handleChange} 
  16. /> 

Using React Hooks:

  1. import React, { useState} from 'react' 
  2. import { TextField } from '@material-ui/react' 
  3.  
  4. function MyComponent(props) { 
  5. const [myValue, setValue] = useState('') 
  6.  
  7. return ( 
  8. value={myValue} 
  9. onChange={(e) => setValue(e.target.value)} 
  10. /> 

In the second example you use much less code becuase React (as of 16.8) understands the pattern you are trying to implement in the “Traditional” example and makes it easier for you.

Happy Coding!

De Hoem Flemister

Qual é a diferença entre o Snapdragon 720G da Qualcomm e o Snapdragon 765G? :: Você compra Moto G7 sobre Xiaomi Redmi nota 7?