How to make Material UI TextField to have same width as content?

Based on docs: looks like material ui can only do fullWidth or fixed width. I would like the width to be same as the content in it. e.g. if its a long url text box I want it to be of the length of the url.

1 answer

  • answered 2018-02-13 02:36 Prakash Kandel

    You should control the width of your parent div if you want to make changes to your textField, Here is one example where you are changing the width as you type a word. Keep in mind that this is just an example, your logic should be different,

    class Example extends React.Component {
      constructor(props) {
        super(props);
        this.state = { width: 20 }
      }
    
    handleChange = () => {
        if(this.state.width === 80){
        return;
        }
        this.setState({ 
        width: this.state.width + 10
      });
    
    }
    
      render() {
        return (
          <div >
            <div style={{width: `${this.state.width}%`}}>
                <TextField name="email" hintText="Email" fullWidth onChange={this.handleChange}/>
              </div>
              <TextField name="pwd" type="password" hintText="Password" />
          </div>
        );
      }
    }
    

    Try here https://jsfiddle.net/prakashk/14dugwp3/37/#&togetherjs=h6bNchy1iw