Reputation: 777
I am creating a UI using Google's Material-UI and React. After creating a page that needs input from Material-ui's TextFields, I need to reset the fields on the click of a material-ui button. Can someone guide me on how to implement this?
Here is my code:
import React from 'react';
import TextField from 'material-ui/TextField';
const Page = () => {
return (
<div>
<h3>Location > Child Location</h3>
<div className="row">
<div className="col-xs-12 col-sm-12 col-md-12 col-lg-12 col-md m-b-15">
<div>
<p>Some paragraph</p>
</div>
</div>
</div>
<div className="row">
<div className="col-xs-12 col-sm-3 col-md-3 col-lg-3 col-md m-b-15">
<p>Name of the text field</p>
</div>
<div className="col-xs-12 col-sm-4 col-md-4 col-lg-4 m-b-15">
<TextField
hintText="Text field..."
fullWidth={true}
/>
</div>
</div>
</div>
);
};
The updated code after the suggestions:
import React, from 'react';
import FlatButton from 'material-ui/FlatButton';
import TextField from 'material-ui/TextField';
export default class Page extends React.Component {
constructor(props) {
super(props)
this.state = {
data: {
firstName: '',
}
}
this.handleReset = this.handleReset.bind(this);
}
handleReset() {
this.setState({
data: {
firstName: '',
}
})
}
render () {
const { data } = this.state;
return (
<div>
...
<TextField
hintText="Text field..."
fullWidth
value={data.firstName}
/>
<FlatButton label="Reset values" onClick={this.handleReset} />
</div>
...
)
}
}
Upvotes: 0
Views: 1393
Reputation: 7424
I'm assuming you are storing those values somewhere (for example state).
class Page extends React.Component {
constructor(props) {
super(props)
this.state = {
data: {
firstName: '',
}
}
this.handleChange = this.handleChange.bind(this)
this.handleReset = this.handleReset.bind(this)
}
handleChange(event) {
this.setState({
data: {
firstName: event.target.value
}
})
}
handleReset() {
this.setState({
data: {
firstName: '',
}
})
}
render() {
const { data } = this.state
return (
<div>
<input type="text" onChange={this.handleChange} value={data.firstName} />
<button onClick={this.handleReset}>Reset values</button>
</div>
)
}
}
ReactDOM.render(
<Page />,
document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Upvotes: 1
Reputation: 109
First of all its better to use 'Controlled inputs', which means you save the value in the state/store and pass it to the input, then handle input onChange to update that value, so whenever you want to reset it, you simply clear that state of yours.
the second way might be using the refs to select the DOM input and clear it which isn't the best way.
Upvotes: 0