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:
- ...props,
- onChange={(event) => someHandlerFunction(event.target.value)}
- />
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
- import React from 'react'
- import { TextField } from '@material-ui/react'
- class MyComponent extends React.Component {
- state = {
- myValue: '',
- }
- handleChange = (e) => this.setState({
- myValue: e.target.value
- })
- render() {
- return (
- value={this.state.myValue}
- onChange={this.handleChange}
- />
- )
- }
- }
Using React Hooks:
- import React, { useState} from 'react'
- import { TextField } from '@material-ui/react'
- function MyComponent(props) {
- const [myValue, setValue] = useState('')
- return (
- value={myValue}
- onChange={(e) => setValue(e.target.value)}
- />
- )
- }
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!
Artigos semelhantes
- What mobile games do you play daily and what keeps you coming back. If you could improve the game, what would you add?
- Do you watch anime and if so, which anime do you watch (sorry if you answered this already I'm new to Quora)?
- Qual é o metal ou material de ficção mais forte? Qual é o material ou metal ficcional mais forte?
- Quais são as diferenças entre as várias estruturas front-end de design de materiais? (Material Ui, Material Angular, Polímero - o que é melhor?)