I use a controlled text field, in order to listen to the change of value in this field and to force the value in the case where the entry is requested in upper or lower case.
So I have to use the value property of the component state.
Unfortunately, in case of I am using this component in another Redux component and want to update this field through the properties connected to the global status of Redux, I don't know how.
If I use the properties of my component in order to value my controlled field, after the onChange of the field, I lose the modifications linked to the entry (because I do not value by value with the state).
If I use the state in the valuation of my controlled field, the value provided by the Redux props is simply not retrieved. Any ideas?
Simplified code snippets of my component:
import { TextField } from '@material-ui/core';
import React from 'react';
import {
MyInputProperties,
defaultInputFieldPropsValue
} from './MyInputProperties';
import { MyInputState } from './MyInputState';
export class MyInput
extends React.Component<MyInputProperties, MyInputState> {
static readonly VERSION: number = 100;
public static defaultProps = defaultInputFieldPropsValue;
constructor(props: MyInputProperties) {
super(props);
this.state = {
...this.state,
value: this.props.value
};
}
protected render(): JSX.Element {
const {
error,
focused,
helperText,
label,
required,
type,
textTransform,
style,
value: propValue
} = this.props;
const { value: stateValue } = this.state;
const element = (
<TextField
inputProps={{ style: { textTransform: textTransform } }}
id={this.id}
disabled={this.isDisabled}
error={error}
focused={focused}
helperText={helperText}
label={label}
onChange={this.handleChange.bind(this)}
required={required}
style={style}
type={type}
defaultValue={propValue}
value={stateValue}
/>
);
return element;
}
private formatValue(value?: string): string | undefined {
const { textTransform } = this.props;
let curValue = value;
if (curValue && textTransform) {
if (textTransform === 'uppercase') {
curValue = curValue.toUpperCase();
} else if (textTransform === 'lowercase') {
curValue = curValue.toLowerCase();
}
}
return curValue;
}
/**
* Callback fired when changing the value.
* @param event Change event
*/
private handleChange(event: React.ChangeEvent<HTMLInputElement>): void {
const value = event.target.value;
this.setState({ value: this.formatValue(value) });
}
}