score:99
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
textarea
s are populated from this initial state - changes to the textareas are propagated to the
state
via thehandlechange
callback. - the
state
is accessed from theonclick
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()
Source: stackoverflow.com
Related Query
- How get data from material-ui TextField, DropDownMenu components?
- How to get input value of TextField from Material UI without using onChange event?
- How to get input value of TextField from Material UI?
- React: How to get values from Material-UI TextField components
- How to get value from Material UI textfield after pressing enter?
- How to get the data from Redux store using class components in React
- How to get custom data attributes values in `MenuItem` from `Select` in material ui?
- How can I get and store Data from Textfield in Form Container?
- how to get the data from child component in stepper in react material ui?
- How to get simultaneously data from 2 forms in react-hook-form from different components
- How to get the data from React Context Consumer outside the render
- How to get values from child components in React
- How can I get data from a local file into my React app?
- How to get data from JSON with Axios?
- How to get form data from input fields in React
- how to import data in react from a js file to use in components
- Gatsby + Markdown: How to get data from a specific markdown file into a single page?
- How can i get postmessage data from react?
- react-query: how to get the data from useQuery in onSuccess callback?
- Draft.js. How to get all entities data from the ContentState
- How do I access data returned from an axios get to display on a web page using react js?
- How to get data from local json file using actions and axios.get() (Redux)?
- How to get the response data from promise in React?
- How to get updated data from apollo cache
- How can I get dynamic data from within gatsby-config.js?
- How to get the data from excel in JSON format in ReactJS?
- How to fetch data in getInitialProps with redux-saga.Then get the response from redux store while in the getInitialProps method?
- How to get value of Date Picker from Material Ui
- How to test children components get proper context from parent's getChildContext()?
- How can i get array of object from this data for state and count in reactjs
More Query from same tag
- Using web3modal in class component shows state error
- Isomorphic React with Webpack's resolve.root option
- React onChange being used after a click of a button to alter value in input
- Unable to implement ZingChart-React
- First onchange checkbox execution doesn't run correctly function React Native Help pls
- Clipboard API and inconsistent browser behaviors between OSes
- Using props and other attributes with react component definition
- Iterate loop over state object with an array key in React
- Accessing this.props function in react ComponentDidMount
- Place icon right next to it and in the center
- How to loop through string and check if there are unmatched letters
- Can a Redux action affect multiple parts of the state tree?
- How to display dynamic events in react-big-calendar?
- Product page do not show products image and contents
- react-router-dom with TypeScript
- Why do I have to put bundle.js script in html when running webpack-dev-server
- TypeError: (node.text || []).map is not a function
- Add class to correct option
- Removing item from the api react hooks
- ReactJS when using HTML attribute checked, reactjs is not allowing to select the checkbox
- React - Using ternary to apply CSS class in functional component
- React conditional onClick with ampersand
- If a function updates a state variable which is an object and is called from a child component, what's the best way to avoid infinite renders?
- Receiving status 400 when fetching with React Hook Form
- How to import js file to React component?
- Nested Match routes with React Router v4 and MatchWithFade
- React how to create sub pages with react router to display?
- React PropTypes.array has keys with type string
- Why doesn't React update dom properly?
- hover underline - react router link vs styled-component link