Parent: (The TextField component is a styled input element from office-ui-fabric-react: Link)
<Searchbar>
<TextField label="Account ID" />
<TextField label="Account Name" />
</Searchbar>
Searchbar component:
export default class Searchbar extends React.Component<ISearchbarProps, ISearchbarState> {
private _searchfields: React.ReactNode[];
public constructor(props: ISearchbarProps) {
super(props);
this.state = {
searchValues: {},
};
this._handleChange = this._handleChange.bind(this);
this._getChild = this._getChild.bind(this);
this._getChild();
}
private _handleChange(event: any, field: string) {
const searchValues = this.state.searchValues;
searchValues[field] = event.target.value;
this.setState({ searchValues });
console.log(this.state.searchValues);
}
private _getChild(): void {
let fielCounter = 0;
this._searchfields = React.Children.map(this.props.children, (child: any) => {
if (child.type.displayName === 'StyledTextFieldBase') {
const searchValues = this.state.searchValues;
const fieldname = child.props.label.replace(/\s/g, "") + fielCounter++;
searchValues[fieldname] = "";
this.setState({ searchValues });
return React.cloneElement(child, {
value: this.state.searchValues[fieldname],
onChange: (e) => this._handleChange(e, fieldname)
});
}
});
}
public render(): React.ReactElement<ISearchbarProps> {
return (
<div>{this._searchfields}</div>
);
}
}
The Problem:
When I type something into the input element, the state console output in the _handleChange shows the updated state, but the input value stays the same as I wouldn't type anything.
Also each letter gets remove from the state. So if I type "test", the console would output "t", "e", "s", "t"
What am I doing wrong?