Reputation: 132
I've been trying to code a controlled TextField component in the standard way just like in React docs:
handleChange(event) {
this.setState({
text: event.target.value
});
}
<TextField label='Enter Text' value={this.state.text} onChange={this.handleChange}/>
The code above is what I've been using, but it seems that it doesn't change the state of the react component, because in the same form if I change a controlled checkbox, it resets the textfield to be empty. If I use a standard html input element it works just as expected and doesn't clear the field.
What am I doing wrong here? Shouldn't TextField work the same way as a text type input?
Upvotes: 4
Views: 6739
Reputation: 412
I do not know what you want to do but ... If what you need is to pass the input value to a text label, you can do it this way:
First you must declare an interface outside of your class
interface myState {
value1: string;
}
you must include your Interface in the class.
class TextFieldControlledExample extends React.Component<{}, myState> {...}
I suppose that for TypeScript themes you must publicly declare the interface of which you are using.
public state: myState = { value1: ''};
you must declare a function within the render to assign the value of the state
public render() {
const { value1 } = this.state;
in this way you assign the value of your inputs. but to update it you have to create a function and call it on the onChange
<TextField
label="Enter Text"
value={this.state.value1}
onChange={this._onChange}
styles={{ fieldGroup: { width: 300 } }}
/>
<Text variant='xxLarge' nowrap block>
{value1}
</Text>
to assign the input value to the state you have declared using setState. must do a function.
private _onChange = (ev: React.FormEvent<HTMLInputElement>, newValue?: string) => {
this.setState({ value1: newValue || '' });
};
You can see the example working here https://codepen.io/jasp402/pen/EBWBgO
Upvotes: 1