score:99

Accepted answer

add an onchange handler to each of your textfield and dropdownmenu elements. when it is called, save the new value of these inputs in the state of your content component. in render, retrieve these values from state and pass them as the value prop. see controlled components.

var content = react.createclass({

    getinitialstate: function() {
        return {
            textfieldvalue: ''
        };
    },

    _handletextfieldchange: function(e) {
        this.setstate({
            textfieldvalue: e.target.value
        });
    },

    render: function() {
        return (
            <div>
                <textfield value={this.state.textfieldvalue} onchange={this._handletextfieldchange} />
            </div>
        )
    }

});

now all you have to do in your _handleclick method is retrieve the values of all your inputs from this.state and send them to the server.

you can also use the react.addons.linkedstatemixin to make this process easier. see two-way binding helpers. the previous code becomes:

var content = react.createclass({

    mixins: [react.addons.linkedstatemixin],

    getinitialstate: function() {
        return {
            textfieldvalue: ''
        };
    },

    render: function() {
        return (
            <div>
                <textfield valuelink={this.linkstate('textfieldvalue')} />
            </div>
        )
    }

});

score:0

class content extends react.component {
    render() {
        return (
            <textfield ref={(input) => this.input = input} />
        );
    }

    _dosomethingwithdata() {
        let inputvalue =  this.input.getvalue();
    }
}

score:3

i don't know about y'all but for my own lazy purposes i just got the text fields from 'document' by id and set the values as parameters to my back-end js function:

//index.js

      <textfield
        id="field1"
        ...
      />

      <textfield
        id="field2"
        ...
      />

      <button
      ...
      onclick={() => { printit(document.getelementbyid('field1').value,
      document.getelementbyid('field2').value)    
      }}>


//printit.js

export function printit(text1, text2) {
console.log('on button clicked');
alert(text1);
alert(text2);
};

it works just fine.

score:3

in 2020 for textfield, via functional components:

const content = () => {
   ... 
      const textfieldref = useref();

      const readtextfieldvalue = () => {
        console.log(textfieldref.current.value)
      }
   ...
  
      return(
       ...
       <textfield
        id="mytextfield"
        label="text field"
        variant="outlined"
        inputref={textfieldref}
       />
       ...
      )

}

note that this isn't complete code.

score:4

here's the simplest solution i came up with, we get the value of the input created by material-ui textfield :

      create(e) {
        e.preventdefault();
        let name = this.refs.name.input.value;
        alert(name);
      }

      constructor(){
        super();
        this.create = this.create.bind(this);
      }

      render() {
        return (
              <form>
                <textfield ref="name" hinttext="" floatinglabeltext="your name" /><br/>
                <raisedbutton label="create" onclick={this.create} primary={true} />
              </form>
        )}

hope this helps.

score:5

faced to this issue after a long time since question asked here. when checking material-ui code i found it's now accessible through inputref property.

...
<csstextfield
  inputref={(c) => {this.myrefs.username = c}}
  label="username"
  placeholder="xxxxxxx"
  margin="normal"
  classname={classes.textfield}
  variant="outlined"
  fullwidth
/>
...

then access value like this.

  onsaveuser = () => {
    console.log('saving user');
    console.log(this.myrefs.username.value);
  }

score:6

flson's code did not work for me. for those in the similar situation, here is my slightly different code:

<textfield ref='mytextfield'/>

get its value using

this.refs.mytextfield.input.value

score:6

the strategy of the accepted answer is correct, but here's a generalized example that works with the current version of react and material-ui.

the flow of data should be one-way:

  • the initialstate is initialized in the constructor of the myform control
  • the textareas are populated from this initial state
  • changes to the textareas are propagated to the state via the handlechange callback.
  • the state is accessed from the onclick callback---right now it just writes to the console. if you want to add validation it could go there.
import * as react from "react";
import textfield from "material-ui/textfield";
import raisedbutton from "material-ui/raisedbutton";

const initialstate = {
    error: null, // you could put error messages here if you wanted
    person: {
        firstname: "",
        lastname: ""
    }
};

export class myform extends react.component {

    constructor(props) {
        super(props);
        this.state = initialstate;
        // make sure the "this" variable keeps its scope
        this.handlechange = this.handlechange.bind(this);
        this.onclick = this.onclick.bind(this);
    }

    render() {
        return (
            <div>
                <div>{this.state.error}</div>
                <div>
                    <textfield
                        name="firstname"
                        value={this.state.person.firstname}
                        floatinglabeltext="first name"
                        onchange={this.handlechange}/>
                    <textfield
                        name="lastname"
                        value={this.state.person.lastname}
                        floatinglabeltext="last name"
                        onchange={this.handlechange}/>
                </div>
                <div>
                    <raisedbutton onclick={this.onclick} label="submit!" />
                </div>
            </div>
        );
    }

    onclick() {
        console.log("when clicking, the form data is:");
        console.log(this.state.person);
    }

    handlechange(event, newvalue): void {
        event.persist(); // allow native event access (see: https://facebook.github.io/react/docs/events.html)
        // give react a function to set the state asynchronously.
        // here it's using the "name" value set on the textfield
        // to set state.person.[firstname|lastname].            
        this.setstate((state) => state.person[event.target.name] = newvalue);

    }

}


react.render(<myform />, document.getelementbyid('app'));

(note: you may want to write one handlechange callback per mui component to eliminate that ugly event.persist() call.)

score:7

try this,

import react from 'react';
import {usestate} from 'react';

import textfield from '@material-ui/core/textfield';

const input = () => {
    const [textinput, settextinput] = usestate('');

    const handletextinputchange = event => {
        settextinput(event.target.value);
    };
    
    return(
        <textfield
            label="text input"
            value= {textinput}
            onchange= {handletextinputchange}
        />
    );
}

export default input;

explanation if the above code was not clear.

first we create a state to store the text input called textinput and assign it the value ''.

then we return a material ui <textfield /> component whose value attribute is set to the textinput state. doing this we display the current value of the textinput in the <textfield />. any changes to the value of textinput will change the value attribute of the <textfield />, courtesy of react.

then we use the onchange attribute of <textfield /> to run a handler function every time the value of the <textfield /> value attribute changes. this handler function is an arrow function stored in the constant handletextinputchange. it takes an event as an argument. when the onchange attribute runs the handler function, it sends the event as an argument to the handler function.

the value of the <textfield /> is stored in event.target.value. we then use the settextinput method of the state to set the state to the value attribute of the <textfield />. thus this change is reflected in the <textfield /> whose value attribute is the value of the textinput state.

thus the data input into the <textfield /> is stored in the state textinput, ready to be used when required.

score:14

here all solutions are based on class component, but i guess most of the people who learned react recently (like me), at this time using functional component. so here is the solution based on functional component.

using useref hooks of reactjs and inputref property of textfield.

    import react, { useref, component } from 'react'
    import { textfield, button } from '@material-ui/core'
    import sendicon from '@material-ui/icons/send'

    export default function multilinetextfields() {
    const valueref = useref('') //creating a refernce for textfield component

    const sendvalue = () => {
        return console.log(valueref.current.value) //on clicking button accesing current value of textfield and outputing it to console 
    }

    return (
        <form novalidate autocomplete='off'>
        <div>
            <textfield
            id='outlined-textarea'
            label='content'
            placeholder='write your thoughts'
            multiline
            variant='outlined'
            rows={20}
            inputref={valueref}   //connecting inputref property of textfield to the valueref
            />
            <button
            variant='contained'
            color='primary'
            size='small'
            endicon={<sendicon />}
            onclick={sendvalue}
            >
            send
            </button>
        </div>
        </form>
    )
    }

score:76

use the accepted answer / this was the answer to another (already deleted) question

@karopastal

add a ref attribute to your <textfield /> component and call getvalue() on it, like this:

component:

<textfield ref="myfield" />

using getvalue:

this.refs.myfield.getvalue()

Related Query

More Query from same tag