Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get input value of TextField from Material UI without using onChange event?

I tried to use this.refs.myField.getValue() or this.refs.myTextField.input.value. But, they are depreciated.

I don't want to use onChange inside TextField, I just convert the text when clicking button Convert

import React from 'react';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';

class Test extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      text: '',
    };
  };

  handleConvertString = (event) => {
    let str = this.refs.myField.getValue();
    this.setState({
      text: str.replace(/[dog]/gi, ''),
    })
  };
  render() {
    return (
      <div>
        <TextField
          ref="myField"
          fullWidth
        />
        <Button variant="outlined" href="#outlined-buttons" onClick={this.handleConvertString}>
          Convert
        </Button>
        <h1>{this.state.text}</h1>
      </div>
    )
    }
}

export default Test;
like image 648
Vu Le Anh Avatar asked Jan 26 '23 07:01

Vu Le Anh


2 Answers

Take a look at the MUI text field API docs.

You are trying to access the underlying value of the text area, so you need the ref of the HTML DOM element.

For the text area, use:

<TextField
  inputRef={ref => { this.inputRef = ref; }}
  fullWidth
/>

And then in your method access the value with this.inputRef.value.

like image 64
RobertMcReed Avatar answered May 03 '23 22:05

RobertMcReed


const { register, handleSubmit } = useForm(); 
<form onSubmit={handleSubmit(formSubmit)}>
              <label>
                
              <TextField
                  id="outlined-basic"
                  label="email"
                  name="email"
                  fullWidth
                  variant="outlined"
                  inputRef={register}
                  required
                />
              </label>
              <br />
              <label>
                <br />
                
                <TextField
                  id="outlined-secondary:cyan"
                  label="password"
                  name="password"
                  type="password"
                  fullWidth
                  variant="outlined"
                  inputRef={register}
                  required
                />
              </label>

              <br />
              <br />

              <Button
                className={classes.root}
                variant="contained"
                color="primary"
                fullWidth
                type="submit"
              >
                Login
              </Button>
             
            </form>

Then handling it with :

const formSubmit = (data) => {
    // Post Data
    const postData = {
      email: data.email,
      pass: data.password,
    };

    console.log(data)
like image 22
DudeHuge Avatar answered May 03 '23 23:05

DudeHuge