In a React app I have a couple of working components like this one:
<div className="form-group col-md-6">
<label className='inp-lbl'>{utl.nameWord()}</label>
<div className='inp-name'>
<input
type="text"
ref="name"
defaultValue={this.name}
onChange={e => {
this.setState((state) => {
return {name: e.target.value};
});
}}
/>
</div>
</div>
Instead of repeating similar code for each or them, I want to extract a generic component that I will be able to reuse; but it does not work as I expect. Here is the new component I made:
class InputField extends React.Component {
constructor(props) {
super(props);
this.state = {
labelStr: props.lbStr,
nameStr: props.nmStr,
defltVal: props.dfVl,
onChgFnc: props.onChFn
};
// this.onChgFnc = props.onChFn
}
render() {
return (
<React.Fragment>
<div className="form-group col-md-6">
<label className='inp-lbl'>{this.state.labelStr}</label>
<div className='inp-name'>
<input
type="text"
ref={this.state.nameStr}
defaultValue={this.state.defltVal}
onChange={this.state.onChgFnc}
/>
</div>
</div>
</React.Fragment>
)
}
}
And this is how I call the new component:
<InputField lbStr={utl.nameWord()} nmStr='name'
dfVl={this.name}
onChFn={handleChange} />
The function handleChange is defined as:
function handleChange(event) {
this.setState((state) => {
return {name: event.target.value};
})
}
Though I thought this should work, it does not. So it would be great if somebody could spot the mistake I am making and let me know.