12

I am building a little chat application.i have used Material UI TextField to input user message. but i can't refer it. I read about this. they said that they do not support for refs. this is my code. and it works.

class App extends Component {
  constructor() {
    super();
    this.state = {
      q: "default"
    };

  }
  handleChanges(val) {
    this.setState({ q: val });
  }
  handleSearch(val) {
    this.setState({ q: val });
    console.log(this.state.q);
  }
  render() {
    return (
      <div className="App">
        <h1>  {this.state.q}</h1>
        <Row className="show-grid">
          <Col sm={2} md={4} className="contact"><h5>contact</h5><br /></Col>
          <Col sm={10} md={8} className="chat grid-border"><h5>chat</h5><br />
            <div className="history"></div>
            <div className="message top-border">

              <input type="text" ref="question" onChange={(e) => { this.handleChanges(this.refs.question.value) }} />
              <MuiThemeProvider>
                <FlatButton label="Primary" primary={true} onTouchTap={(e) => { e.preventDefault(); this.handleSearch(this.refs.question.value); }} />
              </MuiThemeProvider>

            </div>
          </Col>
        </Row>{/*show-grid ends here*/}
      </div>
    );
  }
}
export default App;

If i used this material UI TextField instead of native HTML input tag it does not get the value from the reference.

<MuiThemeProvider>
       <TextField hintText="Ask your question" fullWidth={true} multiLine={true} rows={2} rowsMax={4} type="text" ref="question" onChange={(e) => { this.handleChanges(this.refs.question.value) }}/>
</MuiThemeProvider> 

Is there any workaround or alternative UI library for this ?

7 Answers 7

14

You can also use inputRef. This prop is available from material 1.0.

<TextField
   className={classes.textField}
   inputRef={input => (this._my_field = input)}
   label="My field"
   fullWidth
   margin="normal"
   defaultValue={this.props.my_field}
   onChange={this.handleChange("dhis_password")}
/>

The on change let’s you update the state when it changes, but if you need to get the value unchanged, then the inputRef is necessary.

Also have a look at You can see this How to get password field value in react's material-ui

0
5

Try the following

    let emailRef =React.createRef();

in the material-ui input field use inputRef

 <TextField label="Email Address" name="email" inputRef ={emailRef} />

Just use inputRef not ref

4

if you are using a stateless functional component with material ui then you can use react hooks.

import React, { useState, useRef } from "react";

let MyComponent = (props) => {

  let textInput = useRef(null);

  return (
    <div>
      <Button
        onClick={() => {
          setTimeout(() => {
            textInput.current.focus();
            textInput.current.click();
            textInput.current.value="myname";
          }, 100);
        }}
      >
        Focus TextField
      </Button>
      <TextField
        fullWidth
        required
        inputRef={textInput}
        name="firstName"
        type="text"
        placeholder="Enter Your First Name"
        label="First Name"
      />
    </div>
  );
};
3

This way of referencing elements is deprecated. See https://facebook.github.io/react/docs/refs-and-the-dom.html

Try using this:

<TextField hintText="Ask your question" fullWidth={true} multiLine={true} rows={2} rowsMax={4} type="text" ref={(input) => { this.input = input; }} onChange={(e) => { this.handleChanges(this.refs.question.value) }}/>

And reference the TextField as this.input

If you want to get the TextField value, use this.input.getValue()

I did something like that here.

2
  • It works, may be something with your code. Can you share your code? Sep 30, 2017 at 17:32
  • Hi Adrian, are you using a Class element, or a Pure element? Can you share some fiddle? Dec 9, 2018 at 13:23
1

In onChange method, you don't need to use ref to access value of same textfield, material-ui TextField pass 2 parameters in onChange method:

event, value

So you can write it like this without using ref:

<TextField ... onChange={(e, value) =>  this.handleChanges(value) }/>

As per DOC:

onChange: function

Callback function that is fired when the textfield's value changes.

Signature: function(event: object, newValue: string) => void

event: Change event targeting the text field.

newValue: The new value of the text field.

1
  • Good solution. If we add another <TextField> element, the same method would not work. Would need to write a duplicate method. Ideally with refs, given ref="a" and ref="b" on 2 TextFields, we could just check this.refs.a.value and this.refs.b.value in the setState method, but this doesn't work with Material UI.
    – curtybear
    Dec 17, 2017 at 1:34
0

This solution allows for multiple TextField elements, accessible by the this.(name) accessible inside the class.

We can still use ref, but have to by passing in a function and adding another property on the class (not on props, refs, or state, but on the class itself). Material UI provides a .getValue() method from which we can retrieve the value.

class App extends Component {
...
handleQuestion() {
    this.setState({
        q : this.question.getValue(),
        /** add more key/value pairs for more inputs in same way **/
    })
}
...
<MuiThemeProvider>
   <TextField 
      hintText="Ask your question"
      fullWidth={true} 
      multiLine={true} 
      rows={2} 
      rowsMax={4} 
      type="text" 
      ref={(q) => { this.question = q; }}
      onChange={ this.handleQuestion }
    />
</MuiThemeProvider> 



}
0

I have TextField inside MenuItem, which is hidden by default, so I can't use the opening menu event, because input field is not yet rendered

The only way works for me is watching variable with DOM element

  const [textInput, setTextInput] = useState(null);

  useEffect(() => {
    if (textInput) {
      textInput.focus();
    }
  }, [textInput]);

  return (
    <MenuItem>
      <TextField
        inputRef={setTextInput}
      />
    </MenuItem>
  );

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.