Reputation: 23
I am trying to pass a formatting function to a component with child elements. I'm getting lost in how to set the state.
To start with, I have a couple of elements in a component:
const InputWithLabel = ({ labelText, value, name, onChange, }) => (
<div>
<label>{labelText}</label>
<input name={name} value={value} onChange={onChange} />
</div>
);
Then I have a component I'd like to use to contain them, and add formatting to the entered values in the Input:
class FormatInput extends Component {
constructor( props ){
super( props );
this.state = {};
this.onChange = this.onChange.bind(this);
}
onChange(event) {
const originalValue = event.target.value;
const newValue = this.props.applyFormat(originalValue);
this.setState({[event.target.name]: newValue});
}
render() {
return (
<InputWithLabel
name="IWL"
labelText="Input With Label"
onChange={this.onChange}>
</InputWithLabel>
);
}
}
I'm calling from a simple homepage, like so:
<FormatInput name="FI" applyFormat={(arg)=> arg *=2}></FormatInput>
Entering values into the Input in the homepage doesn't have any effect (i.e. doesn't get multiplied by 2). Stepping through the code, it doesn't throw any errors, so I'm not sure where it fails.
On inspection, the FormatInput's state is not set unless I explicitly set it in the constructor, even though the state should contain whatever value is entered. But I don't understand how the FormatInput component is able to get that state, to update it, so I guess the question is, how can I update the state of the child component?
Upvotes: 2
Views: 59
Reputation: 33141
It may be the way you have written your question, but you need to set the value
attribute for <InputWithLabel>
. Not sure which state key to give it though because you are using event.target.name
, and i'm not sure why.
Maybe you could do something like:
this.state = {
formattedValue: ''
}
...
this.setState({ formattedValue: newValue })
...
<InputWithLabel
value={this.state.formattedValue}
name="IWL"
labelText="Input With Label"
onChange={this.onChange}>
</InputWithLabel>
Also inside your formatter, you should remove the equal sign to (arg) => arg * 2
. With the equals sign there, you are saying to multiply the argument by 2 and then store it in arg, where as you just want to return the modified value.
Upvotes: 1