I have a re-usable <FormInput>
react component that’s used to render input
elements across a large web application.
It calls an onChange()
handler after each change and passes the current input.value
to it.
Here’s a basic version of the component:
import PropTypes from 'prop-types';
import React from 'react';
class FormInput extends React.Component {
static propTypes = {
initialValue: PropTypes.string,
name: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired
};
static defaultProps = {
initialValue: ''
};
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
this.state = {
inputValue: props.initialValue
};
}
onChange(e) {
// After setState completes, we call the `onChange` handler that was
// passed by the parent, with the current input value as the only arg
const afterSetState = () => {
this.props.onChange(this.state.inputValue);
}
this.setState(
{ inputValue: e.currentTarget.value },
afterSetState.bind(this)
);
}
render() {
return (
<input
onChange={this.onChange}
value={this.state.inputValue}
type='input'
name={this.props.name}
/>
);
}
}
export default FormInput;
I have a parent component that calls this <FormInput>
child component. I have a situation where I want the parent component to be able to clear/reset the value on this <FormInput>
child component.
If I change the initialValue
prop passed in to this component, it does nothing since that’s only used “once” to set the initial value for the state
. Perhaps if the whole component were forced to re-render, would it “reset” the whole component and accomplish this?
I’m struggling with this because as you can see, this component manages its own state
with the current value. And I can’t change this component to have it’s value managed externally or by a parent, since it’s used in numerous places in our application and is a shared component.
Is there an accepted way to accomplish this without inverting the responsibility of this component?
Thanks!